在SQL Server中,我想为此做点什么......
DECLARE @Values varchar(1000)
SET @Values = 'A, B, C'
SELECT
blah
FROM
foo
WHERE
myField IN (@Values)
这可能或如何实现这个目标吗?
答案 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]