Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hi,
my sql command is like this:

SQL
DECLARE @str nvarchar='1,2,3,4,5,6,7'
SELECT * FROM mytable
WHERE ID IN (@str)


but the result is the first row(id=1)
how can retrieve all row (1,2,3,4,5,6,7)
i use sql server 2008
Posted
Updated 13-Apr-13 4:42am
v2
Comments
gvprabu 14-Apr-13 13:48pm    
Hi...
In Variable Declaration place, U didn't gave the nvarchar Size... one thing how u got one row(id=1). With out dynamic Query or other methods u can't get the result.

Unfortunately, you can't do it that simply - it just doesn't work!
You have to go a bit round the houses and convert the CSV to a list that SQL underatsnds - in practice a table of some form. Here's how I do it:
SQL
DECLARE @INSTR as VARCHAR(MAX)
SET @INSTR = '2,3,177,'
DECLARE @SEPERATOR as VARCHAR(1)
DECLARE @SP INT
DECLARE @VALUE VARCHAR(1000)
SET @SEPERATOR = ','
CREATE TABLE #tempTab (id int not null)
WHILE PATINDEX('%' + @SEPERATOR + '%', @INSTR ) <> 0
BEGIN
   SELECT  @SP = PATINDEX('%' + @SEPERATOR + '%',@INSTR)
   SELECT  @VALUE = LEFT(@INSTR , @SP - 1)
   SELECT  @INSTR = STUFF(@INSTR, 1, @SP, '')
   INSERT INTO #tempTab (id) VALUES (@VALUE)
END
SELECT * FROM myTable WHERE id IN (SELECT id FROM #tempTab)
DROP TABLE #tempTab
It's not nice, but it works! :laugh:
 
Share this answer
 
Hi...

Try Dynamic Query as follows.

SQL
DECLARE @str varchar(100)='1,2,3,4,5,6,7', @SqlStr VARCHAR(1000)

CREATE TABLE mytable (ID INT)
INSERT INTO mytable(ID) VALUES(1),(2),(3),(4), (5), (6), (7)

SELECT @Sqlstr='SELECT * FROM mytable
WHERE ID IN ('+@str+')'

PRINT @SqlStr
EXEC(@SqlStr)

DROP TABLE mytable 


Regards,
GVPrabu
 
Share this answer
 
SQL
CREATE FUNCTION [dbo].[SplitDelimited]
(	
	@List nvarchar(MAX),
	@SplitOn nvarchar(20)
)
RETURNS @RtnValue table (
	Value nvarchar(100)
)
AS
BEGIN
	While (Charindex(@SplitOn,@List)>0)
	Begin 
		Insert Into @RtnValue (value)
		Select 
			Value = ltrim(rtrim(Substring(@List,1,Charindex(@SplitOn,@List)-1))) 
		Set @List = Substring(@List,Charindex(@SplitOn,@List)+len(@SplitOn),len(@List))
	End 
	
	Insert Into @RtnValue (Value)
    Select Value = ltrim(rtrim(@List))

    Return
END

DECLARE @str nvarchar(max)='1,2,3,4,5,6,7'

SELECT * FROM myTable WHERE id IN (SELECT Value FROM SplitDelimited(@str))
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900