如何声明一串字符串?

时间:2015-05-22 10:25:03

标签: sql sql-server

BeautifulSoup

尝试通过声明这样的局部变量来执行上述操作:

SELECT * FROM MyTable WHERE MyRow IN ('100','200','300')

有没有办法让这项工作?已经尝试过#34;这样:

DECLARE @What VARCHAR(MAX)
SET @What = '100','200','300'
SELECT * FROM MyTable WHERE MyRow IN (@What)

和此:

SET @What = "'100','200','300'"

第一个是最符合逻辑的,因为除了SQL之外,它几乎可以用于任何其他语言。 SET @What = ('100','200','300') 的长度会有所不同,因此我不能只为每个变量设置一个变量。

如何声明本地字符串变量以包含字符串?

3 个答案:

答案 0 :(得分:4)

这是一种方法,使用表变量:

DECLARE @What TABLE(txt VARCHAR(MAX))
INSERT INTO @What (txt) VALUES ('100'),('200'),('300')
SELECT * FROM MyTable WHERE MyRow IN (SELECT txt FROM @What)

以下是a sqlfiddle来演示上述内容。

答案 1 :(得分:0)

我想如果您将列表作为逗号分隔列表传递然后将其转换为表格会更好。这是一个有效的例子:

DECLARE @What VARCHAR(MAX) = '100,200,300';
DECLARE @XmlData AS XML = CAST(('<X>' + REPLACE(@What, ',', '</X><X>')+'</X>') AS XML);
DECLARE @Test TABLE (What INT);


INSERT INTO @Test
SELECT N.value('.',  'INT') FROM @XmlData.nodes('X') AS T(N);

SELECT *
FROM MyTable AS M
WHERE EXISTS (
    SELECT 1
    FROM @Test AS T
    WHERE T.What = M.MyRow
    );

答案 2 :(得分:0)

你可以写成:

DECLARE @MyTable TABLE (MyRow VARCHAR(MAX))
INSERT INTO @MyTable VALUES ('100'),('200'),('300')


DECLARE @What VARCHAR(MAX)
SET @What = '100,200,300'

declare @xml xml

set @xml = N'<root><r>' + replace(@What,',','</r><r>') + '</r></root>'

SELECT * FROM @MyTable WHERE MyRow IN
(
select 
  t.value('.','varchar(max)') as [MyRow items]
from @xml.nodes('//root/r') as a(t)
)