我有一个存储过程根据不同的参数返回相同的列。
例如;
if name is not null
select a,b,c,d,e,f
from table1, table2, table3
where .....
if age is not null
select a,b,c,d,e,f
from table1, table2, table3,table4
where .....
if city is not null
select a,b,c,d,e,f
from table1,table3,table5
where .....
问题是,当我想添加/省略列时,我需要为每个选择执行此操作。
有没有办法保留列列表一次并将其用于不同的条件?
答案 0 :(得分:2)
您可以使用动态SQL
DECLARE @sql NVARCHAR(4000)
SET @sql = '
select a,b,c,d,e,f
from table1,table3,table5
where 1=1 '
IF @name IS NOT NULL
SET @sql = @sql + ' AND name = ' + @city
IF @age IS NOT NULL
SET @sql = @sql + ' AND age = ' + @age
IF @city IS NOT NULL
SET @sql = @sql + ' AND city = ' + @city
EXEC sp_executesql @sql
答案 1 :(得分:0)
试试这个
SELECT -- select list here
.....
WHERE
name= CASE WHEN @name IS NULL THEN name ELSE @name END
AND age= CASE WHEN @age IS NULL THEN age ELSE @age END
AND city= CASE WHEN @city IS NULL THEN city ELSE @city END