SQL Server
我有一个包含逗号分隔字符串的参数:
'ABC,DEF,GHI'
我想在IN语句中使用该字符串,它将采用我的参数:
select * from tableA where val IN ('abc','def','ghi')
关于如何做到这一点的任何想法?
答案 0 :(得分:1)
如果使用动态SQL是一个选项,则可以执行此操作:
SELECT 'SELECT * FROM tableA WHERE val IN (' +
'''' + REPLACE('abc,def,ghi', ',', ''',''') + ''')'
基本上,REPLACE()
功能会将每个项目分开' ,而不仅仅是,。
答案 1 :(得分:1)
最简单的方法是做这样的事情:
SELECT *
FROM TableName
WHERE ',' + commaDelimitedString + ',' LIKE '%,' + FieldName + ',%'
但要注意SQL注入。您可能想要参数化它。
答案 2 :(得分:0)
您可以使用此SQL来“转移”#39;以逗号分隔的字符串到表中;
DECLARE @badData TABLE (id INT NOT NULL, txt NVARCHAR(max));
INSERT INTO @badData
VALUES (1, 'foo,bar,baz'), (2, NULL);;
-- the idea is to recursively 'pop' a value from the start of the string, splitting it into 'head' and 'tail' components
WITH unpacked (id, head, tail)
AS (
SELECT id, LEFT(txt, CHARINDEX(',', txt + ',') - 1), STUFF(txt, 1, CHARINDEX(',', txt + ','), '')
FROM @badData
UNION ALL
SELECT id, LEFT(tail, CHARINDEX(',', TAIL + ',') - 1), STUFF(tail, 1, CHARINDEX(',', tail+ ','), '')
FROM unpacked
WHERE tail > ''
)
SELECT id, head
FROM unpacked
ORDER BY id
您可以将此结果粘贴到公用表表达式中,然后编写一个where子句,如
select * from tableA where val IN (select head from unpacked)
答案 3 :(得分:-3)
许多编程语言都有split()函数,例如Ruby
'123,456,789'.split ","
=> ["123", "456", "789"]