将变量设置为IN语句的字符串列表
问题描述:
我可以将字符串列表分配给变量以在IN语句中使用而不使用动态SQL?将变量设置为IN语句的字符串列表
我正在SSRS中开发一个报告,它允许用户选择三个可能的值中的一个作为参数,反过来将这个选择值与IN语句相关联。有些参数有一个关联的值,有些有几个参数。
情况1和2运行正常,但情况3并不是因为它是作为标量值而不是列表传递的。我试过各种方式逃避每个项目的引号,但它不起作用。
declare @items as varchar(50)
set @items =
CASE @parameter
WHEN 1 then 'first'
WHEN 2 then 'second'
WHEN 3 then 'third, fourth'
END
select column1
from table1
where column1 IN (@items)
答
不,你不能。您可以使用表变量的方式如下:
DECLARE @table TABLE(item varchar(50))
IF @parameter = 3
BEGIN
INSERT INTO @table(item) VALUES ('third'), ('fourth')
END
ELSE
BEGIN
INSERT INTO @table VALUES(
CASE @parameter
WHEN 1 then 'first'
WHEN 2 then 'second'
END
)
END
-- And use IN(subquery)
SELECT column1
FROM table1
WHERE column1 IN (SELECT item FROM @table)
您也可以使用EXISTS
这在这样的条件检查快很多,但你不会得到显著的性能改进由于小件物品cound(1-2)
SELECT column1
FROM table1 t
WHERE EXISTS (SELECT * FROM @table WHERE item = t.column1)
答
,你可以使用动态SQL(未测试)
declare @items as varchar(50)
set @items =
CASE @parameter
WHEN 1 then '''first'''
WHEN 2 then '''second'''
WHEN 3 then '''third'', ''fourth'''
END
declare @query = 'select column1 from table1 where column1 IN ('[email protected]+')'
exec @query
三重引号是因为字符串连接机制
0去
可能重复[参数化SQL IN子句?](http://stackoverflow.com/questions/337704/parameterizing-a-sql-in-clause)(虽然这并不具体说明报告服务) –