在' IN'中使用用户变量sql的子句

时间:2014-05-20 10:25:15

标签: sql sql-server

declare @A varchar(5000) 
declare @B varchar(5000)

select @A=value from drp.Parameter where parameteridname='IV01'
--result of this query ('DIM003966','DIM000736','DIM025297',
--                                                      'DIM025302','DIM027583')

select [InventLocationId],[WMSLocationId] from ItemKit.InventDim
where inventdimid in (@A)

我没有从第二个查询得到任何结果,但如果我单独运行它们并在第二个中使用第一个查询的结果我得到它。有没有办法一起运行它们

3 个答案:

答案 0 :(得分:2)

您应该使用以下代码:

select [InventLocationId],[WMSLocationId] from ItemKit.InventDim
where inventdimid in (select value from drp.Parameter where parameteridname='IV01')

答案 1 :(得分:2)

这是因为它按原样评估@a(作为文本,而不是值列表)。

您应该动态创建一个sql语句并执行它:

declare @sqlStatement nvarchar(4000)

@sqlStatement = 'select [InventLocationId],[WMSLocationId] from ItemKit.InventDim where inventdimid in (' + @A + ')'

execute sp_executesql @sqlStatement

但正如其他人所说,除非真的有必要,否则不要使用。

答案 2 :(得分:0)

由于您有一个字符串值(包含所有值),您可以:

动态解析SQL

注意:我不推荐这样做,因为它可以允许sql injection (请参阅@Patrick Hofman的答案以获得良好的例子)

使用

declare @A varchar(5000) 
declare @B varchar(5000)

select @A=value from drp.Parameter where parameteridname='IV01'
--result of this query ('DIM003966','DIM000736','DIM025297',
--                                                      'DIM025302','DIM027583')

SELECT @A /* Here you will see the problem, as it is not multiple values, 
             it is a single string with a comma & quote (') delimited list */

SELECT 
    [InventLocationId], [WMSLocationId] 
FROM 
    ItemKit.InventDim
WHERE
    /* parse up the inventdimid to include the quote (') around it */
    @A like '%''' + @inventdimid + '''%'