标题 | sql 数据库中的存储过程的参数问题 |
内容 | 1、sql 数据库中的存储过程的参数问题 怎么将sql数据库中的存储过程中的参数既作为输出变量又作为输出变量? [sql] view plaincopy --drop proc proc_test --go create proc dbo.proc_test @in int, @out int out, @in_out int output as select @out = @in + @in_out, --1 + 2 = 3 @in_out = @out + 1 --3 + 1 = 4 go declare @in_p int declare @out_p int declare @in_out_p int set @in_p = 1; set @in_out_p = 2 exec dbo.proc_test @in_p, @out_p out, @in_out_p output select @in_p, --输入参数 @out_p, --输出参数 @in_out_p --输入,输出参数 /* (无列名) (无列名) (无列名) 1 3 4 */ 2、在存储过程中的参数问题。 下面是问题: [sql] view plaincopy create table #tabletest(id int identity , name varchar(20),age int,) go insert into #tabletest select '小明',23 union all select '小红',28 union all select '小军',27 go select *from #tabletest go create proc proctest @name varchar(20), @age int, @ids varchar(30) as begin select *from #tabletest where 1=1 end --当我传入@name参数等于 小明,23岁,还有id在(1,3)的时候 --我怎么可以弄成可选的参数 --比如,name不为空时候 select *from #tabletest where 1=1 and name like '小明' --如果name参数为空的时候,ids参数不为空的时候 select *from #tabletest where 1=1 and id in(1,3) --请问一下,就有参数不为空的时候存储过程中的sql追加条件,为空的时候就不追加,这样带可选参数的存储过程怎么写,以及怎么调用,请帮小弟写一个实例 这种问题,本质上就是根据传入的参数不同,进行不同的查询,也就是where 后面的查询条件是动态的。 一般有2中处理方式,一种就是写动态语句,但动态语句由于是动态拼接字符串,所以比较难维护,而且如果存储过程需要执行多次,那么每次都需要重新编译,但每次生成的执行计划,应该是比较优化的。但如果拼接字符串部分,只是少量的话,还是可以用动态语句的,下面我的解法就是用动态语句来实现的,结构清晰,易于维护。 另一种,就是通过在where语句后面写case when来进行判断,这种方法的好处是不用动态拼接语句,但不易于理解,也不易于修改,因为别人不一定能理解你这么写的意思。另一个问题就是性能的问题,因为在原来的公司就用过这种方法,一段时间后,查询非常慢,本来几秒就能出结果,后来几分钟都出不了结果。说实在的,这种方法要求较高的技巧性,也容易出错,不建议使用。 下面是我的解法,用了动态语句来实现,但考虑了维护、测试方面的要求: [sql] view plaincopy --drop table #tabletest create table #tabletest(id int identity , name varchar(20),age int,) go insert into #tabletest select '小明',23 union all select '小红',28 union all select '小军',27 go select *from #tabletest go create proc proctest @name varchar(20)=null,@age int = null,@ids varchar(30) = null as declare @sql nvarchar(max); set @sql = ''; set @sql = 'select * from #tabletest where 1 = 1'; set @sql = @sql + case when @name is not null then ' and name like ' + quotename(@name +'%','''') when @age is not null then ' and age = ' + cast(@age as varchar) when @ids is not null then ' and id in (' + @ids +')' else ' ' end --打印出语句 select @sql as '语句' --执行语句 --exec(@sql) go exec proctest /* 语句 select * from #tabletest where 1 = 1 */ exec proctest '小明',23 /* 语句 select * from #tabletest where 1 = 1 and name like '小明%' */ exec proctest @ids = '2,3' /* 语句 select * from #tabletest where 1 = 1 and id in (2,3) */ 备注:如遇到需多个and参数连接查询,sql语句可写如下 set @sql= @sql + case when @sellernick <> '' then ' and sellernick = ' else ' ' end set @sql= @sql + case when @logisticsid <> '' then ' and logisticsid = else ' ' end |
随便看 |
|
在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。