1

我有字符串,我必须从中提取子字符串并查询它们的值。

declare @str varchar(max)
@str='Hello,world,continent,nation,city'

select * from mytable
where col_word in(SELECT REPLACE(@str,',',''','''))

子查询

SELECT REPLACE(@str,',',''',''')

结果是

Hello,'world','continent','nation','city

我希望上面的结果用单引号引起来,以便它可以工作IN

但这仅返回第一个 col_word 值Hello,它是 中的第一个子字符串@str

我应该怎么办 ?

4

2 回答 2

3

尝试这个:

您不能将查询的一部分作为字符串。我们必须将整个查询作为一个字符串,然后使用EXEC()命令执行它.. 或sp_executesql存储过程。推荐后者。

declare @str varchar(max);
select @str='Hello,world,continent,nation,city';

SELECT @str=''''+REPLACE(@str,',',''',''')+''''
exec('select * from mytable where col_word in('+@str +')')
于 2012-11-23T12:38:59.283 回答
1

尝试这个:

declare @str varchar(max)
declare @pattern varchar(max)
SET @str='Hello,world,continent,nation,city'
SELECT REPLACE(@str,',',''',''')
SET @pattern = REPLACE('Hello,world,continent,nation,city', ',', ''',''')
EXEC('select * from mytable where col_word in(''' + @pattern + ''')')
于 2012-11-23T12:45:01.580 回答