SQL查询-设置局部变量(PostgreSQL、MySQL)

😋博主在工作中编写复杂SQL语句时,经常需要替换查询值进行测试。所以需要用到局部变量设置,可以减轻测试时的压力。

目录

使用场景

🤔在user_info表、user_info_ex表、user_info_in表,三个表中查询工号为'STAF0306'的记录并返回,SQL示例如下。

1.常规写法

javascript 复制代码
select 
	user_id, user_name, user_code
from user_info
where
	user_code = 'STAF0306'
	
union 

select 
	user_id, user_name, user_code
from user_info_ex
where
	user_code = 'STAF0306'

union 

select 
	user_id, user_name, user_code
from user_info_in
where
	user_code = 'STAF0306'

2.局部变量写法

如果需要改为查询'STAF0308'的工号时,需要替换三个位置。在简单的语句中替换没有什么影响,但如果在复杂的SQL中,可能会出现漏改的情况😥。

所以,我们可以在顶部显眼位置设置局部参数,直接修改所需的入参,可无视复杂的SQL语句👏。

(1)PostgreSQL示例

🙆‍♂️使用current_setting('parameter_name') 来获取参数值,并注意设置对应的参数类型

javascript 复制代码
SET my.user_code TO 'STAF0308';

select 
	user_id, user_name, user_code
from user_info
where
	user_code = current_setting('my.user_code')::VARCHAR
	
union 

select 
	user_id, user_name, user_code
from user_info_external
where
	user_code = current_setting('my.user_code')::VARCHAR
注意事项
复制代码
1)SET LOCAL 需要在事务块中使用(BEGIN...COMMIT)
2)使用 SET 可以在事务外使用
3)参数值总是字符串,需要根据需要进行类型转换

(2)MySQL示例

🙆‍♀️用户变量以 @ 开头,在会话内有效,注意大小写。

javascript 复制代码
SET @user_code = 'STAF0308';

select 
	user_id, user_name, user_code
from user_info
where
	user_code = @user_code
	
union 

select 
	user_id, user_name, user_code
from user_info_external
where
	user_code = @user_code

union 

select 
	user_id, user_name, user_code
from user_info_in
where
	user_code = @user_code
注意事项
复制代码
1)用户变量以 @ 开头,在会话内有效
2)局部变量在存储过程内使用 DECLARE 定义,不以 @ 开头
3)变量名区分大小写
4)用户变量会在会话结束后自动清除

结语

🎈以上博主仅列出了两种较为简单的设置局部变量方式,还有许多其他的设置方式就不做扩展说明了,感谢阅读。

相关推荐
Database_Cool_4 小时前
OLTP 和 OLAP 区别详解:分析型数据库和事务型数据库怎么选(附阿里云 AnalyticDB MySQL 选型指南)
数据库·mysql·阿里云
Database_Cool_5 小时前
单机 MySQL 迁移到分布式数据库方便吗?阿里云 PolarDB-X 100% MySQL 协议兼容零改造平滑迁移
数据库·分布式·mysql
姜太小白6 小时前
【MySQL】 索引优化实战:解决 WHERE 等值 + IS NULL 查询,TEXT 字段报错 1167 的完整指南
数据库·mysql
liuxiaowei37 小时前
【绝版教程】新版MySQL DBA高级实战进阶班 MySQL8.0 姜承尧-腾讯数据库总监
数据库·mysql·dba
破碎的南瓜7 小时前
sqli--sql注入过关笔记(1,2,3,4,5,9)
数据库·笔记·sql
Csvn9 小时前
📊 SQL 入门 Day 10:递归 CTE — 破解无限层级查询的终极武器
后端·sql
sg_knight9 小时前
MySQL 存储过程详解:从入门到实战
android·数据库·mysql·database·dba·关系型数据库·db
Database_Cool_11 小时前
企业级多模态分析计算引擎选型:首选 AnalyticDB MySQL 向量 + SQL + 实时一体化方案
数据库·sql·mysql
宇宙第一小趴菜13 小时前
五、Oracle vs MySQL 架构深度对比笔记
mysql·oracle·架构
洵有兮13 小时前
sql注入通关笔记
数据库·笔记·sql·sql注入