1

I have string from which I have to extract substring and query on their values.

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

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

The sub query

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

results in

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

I want the above result be enclosed by single quotes so that it can work for IN

But this returns only for first col_word value Hello which is first substring in @str.

What should I do ?

4

2 に答える 2

3

Try this:

You cannot make part of your query as string. We have to make the whole query as a string, then execute it with EXEC() command.. or sp_executesql stored procedure. The latter is recommended.

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

Try this:

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 に答える