I have this string that i am getting from .net application A,B,C,D,E,F,
I wanted to write a sql select statement like
set @string = \'A,B,C,D,E,F\'
You have several options:
IN
statementIN
or better just JOIN
statement (among other implementations I favor SQL User Defined Function to Parse a Delimited String).The you code would be:
select tbl_test.*
from tbl_test
inner join fn_ParseText2Table(@string) x
on tbl_test.code = x.txt_value
SQL
.Create a User Defined Function that takes the string as input and returns a table:
create function [dbo].[f_SplitString] (@str as varchar (1000))
returns @t table (value varchar (50))
etc...
Then adjust your Select statement:
select * from tbl_test
where tbl_test.code in (select value from f_SplitString(@string))
I know this is an old question, but I thought I would post an answer to it anyway. I never liked passing in comma delimited string values, so I have used XML in the past and used a join statement on the xml like so:
declare @xml as xml
set @xml = '<v id="key1" /><v id="key2" /><v id="key3" />'
select
t.*
from
mytable t join @xml.nodes('/*') x(n)
on n.value('@id','varchar(50)') = t.mykey
I think, the easiest way is as below,
Option1:
set @string = '''A','B','C','D','E','F'''
Exec ('select * from tbl_test
where tbl_test.code in ('+@string+')')
Option2:
set @string = '''A','B','C','D','E','F'''
DECLARE @SQL NVARCHAR(MAX)
SET @SQL='select * from tbl_test
where tbl_test.code in ('+@string+')'
exec sp_executesql @SQL;
Very frequently asked question! What you want is a table-valued function.
But don't reinvent the wheel by writing your own, I found dozens just by Googling sql split
. Here's one from Microsoft:
http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=StringArrayInput
I used to use dynamic SQL for this, but that meant I had to dig up the code and copy it into each new app. Now I don't even have to think about it.