设置具有多个值的变量并使用IN

时间:2011-09-15 13:05:49

标签: sql-server tsql

  

可能重复:
  Parameterizing a SQL IN clause?

在SQL Server中,我想为此做点什么......

DECLARE @Values varchar(1000)

SET @Values = 'A, B, C'

SELECT
  blah
FROM 
  foo
WHERE
  myField IN (@Values)

这可能或如何实现这个目标吗?

3 个答案:

答案 0 :(得分:37)

您需要一个表变量:

declare @values table
(
    Value varchar(1000)
)

insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')

select blah
from foo
where myField in (select value from @values)

答案 1 :(得分:2)

创建拆分功能:

CREATE FUNCTION dbo.SplitStrings
(
    @List      NVARCHAR(MAX), 
    @Delimiter NVARCHAR(2)
)
RETURNS @i TABLE(Item NVARCHAR(MAX))   
AS
BEGIN
    DECLARE @x XML;

    SET @x = N'<root><i>' 
        + REPLACE(@List, @Delimiter, '</i><i>') 
        + '</i></root>';

    INSERT @i(Item)
        SELECT RTRIM(i.value('.','nvarchar(max)'))
        FROM @x.nodes('//root/i') AS i(i);

    RETURN;
END
GO

现在你可以说:

DECLARE @Values VARCHAR(1000);

SET @Values = 'A, B, C';

SELECT
  blah
FROM 
  foo
INNER JOIN dbo.SplitStrings(@Values, ',') AS s
  ON s.Item = foo.myField;

答案 2 :(得分:0)

使用Temp Table或Table变量,例如

select 'A' as [value]
into #tmp
union
select 'B'
union 
select 'C'

然后

SELECT   
blah 
FROM    foo 
WHERE   myField IN (select [value] from #tmp) 

SELECT   
f.blah 
FROM foo f INNER JOIN #tmp t ON f.myField = t.[value]