SQL动态参数
- --1. 使用 EXEC 实现的动态参数存储过程
- CREATE PROC p_test
- @para1 varchar(10)=null,
- @para2 varchar(10)=null,
- @para3 varchar(10)=null,
- @para4 varchar(10)=null
- AS
- SET NOCOUNT ON
- DECLARE @sql varchar(8000)
- SET @sql='SELECT * FROM tbname WHERE 1=1'
- IF @para1 IS NOT NULL
- SET @sql=@sql+' AND col1='''+@para1+''''
- IF @para2 IS NOT NULL
- SET @sql=@sql+' AND col2='''+@para2+''''
- IF @para3 IS NOT NULL
- SET @sql=@sql+' AND col3='''+@para3+''''
- IF @para4 IS NOT NULL
- SET @sql=@sql+' AND col4='''+@para4+''''
- EXEC(@sql)
- GO
- /*======================================================*/
- --2. 使用 sp_executesql 实现的动态参数存储过程
- CREATE PROC p_test
- @para1 varchar(10)=null,
- @para2 datetime=null,
- @para3 varchar(10)=null,
- @para4 int=null
- AS
- SET NOCOUNT ON
- DECLARE @sql nvarchar(4000)
- SET @sql='SELECT * FROM tbname WHERE 1=1'
- +CASE WHEN @para1 IS NULL THEN '' ELSE ' AND col1=@para1' END
- +CASE WHEN @para2 IS NULL THEN '' ELSE ' AND col2=@para2' END
- +CASE WHEN @para3 IS NULL THEN '' ELSE ' AND col3=@para3' END
- +CASE WHEN @para4 IS NULL THEN '' ELSE ' AND col4=@para4' END
- EXEC sp_executesql @sql,N'
- @para1 varchar(10)=null,
- @para2 datetime=null,
- @para3 varchar(10)=null,
- @para4 int=null
- ',@para1,@para2,@para3,@para4
- GO
- /*======================================================*/
- --3. 不使用动态 Transact-SQL 语句实现的动态参数存储过程
- CREATE PROC p_test
- @para1 varchar(10)=null,
- @para2 datetime=null,
- @para3 varchar(10)=null,
- @para4 int=null
- AS
- SET NOCOUNT ON
- SELECT * FROM tbname
- WHERE (@para1 IS NULL OR col1=@para1)
- AND (@para2 IS NULL OR col2=@para2)
- AND (@para3 IS NULL OR col3=@para3)
- AND (@para4 IS NULL OR col4=@para4)
============ 欢迎各位老板打赏~ ===========
与本文相关的文章
- · mysql创建用户并赋予权限
- · docker定时任务Mysql脚本
- · docker安装mysql8注意事项
- · 定时备份docker中的mysql
- · docker-compose通过容器名连接mysql
- · unity3d mysql error: The given key was not present in the dictionary.
- · mysql服务性能优化—my.cnf配置说明详解(不同内存)
- · MySQL 批量修改数据表编码及字符集
- · Your database must use ‘READ-COMMITTED’ as the default isolation level.
- · MySQL-InnoDB存储引擎
- · 将数据从mysql迁移到clickhouse
- · docker安装Mysql5.7