2012-11-23 43 views
1

我有字符串,我必须从中抽取子字符串并查询其值。以逗号分隔子字符串SQL Server

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

但这种回报工作仅适用于第一个子字符串i的第一个col_word值Hello n @str

我该怎么办?

+0

不能使用'IN'这样 –

+0

我想以上的结果用单引号括起来,以便它可以为 –

+1

工作'IN'不以逗号分隔的字符串 –

回答

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('[email protected] +')') 
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 + ''')')