SQL存储过程,需要根据传入的参数,更改where语句的条件,请教大虾
假设分别传入参数为1,2,3时
Create Procedure X
@type char(1),
as
if(@type== '1 ') Select id1,id2,id3 from Table_A WHERE id4 like '% 'A ' '% '
if(@type== '2 ') Select id1,id2,id3 from Table_A WHERE id4 like '% 'B ' '% '
if(@type== '3 ') Select id1,id2,id3 from Table_A WHERE id4 like '% 'C ' '% '
本来这样也行,可是我的select非常长,中间夹杂inner join ,cross join等语句,因此想把条件选择放到 like后面,可是这样写却报错,请大侠指点下
Select id1,id2,id3 from Table_A WHERE id4 like (if(@type== '1 ') return '% 'A ' '% '
else if(@type== '2 ') return '% 'B ' '% '
else if(@type== '3 ') return '% 'C ' '% ')
------解决方案--------------------Create Procedure X
@type char(1)
as
declare @sql nvarchar(4000)
set @sql = 'Select id1,id2,id3 from Table_A WHERE id4 like % '
if(@type= '1 ')
set @sql = @sql + 'A ' + '% '
if(@type= '2 ')
set @sql = @sql + 'B ' + '% '
if(@type= '3 ')
set @sql = @sql + 'C ' + '% '
set @sql = @sql + ' ' --这里加上一些语句,例如你要加的like
execute sp_executesql @sql