2

Sorry i am not sure how to titled the question well. I want to select few records in sql where a particular column is a set of strings.

Example . I have a table student and has columns ID and name. ID has records 1,2,3,4,5,6 . NAme has A,B,C,D,E,F.

I want to return C,D,E WHERE ID=[3,4,5].

I tried

SELECT FROM student WHERE ID=2,3,4

it gives error, ID=2,3,4 ='2,3,4' and it reads ID as a single columns. I am confused.

Also in my case, ID set are returned in a storedprocedure variable. that is like @ID

SELECT * FROM STUDENT WHERE ID=@ID 

@ID above is a variable of a string type holding the set {1,2,3}. Please any help would be appreciated.

2
  • 2
    WHERE ID=[3,4,5] That's not valid syntax. You want WHERE ID IN (3, 4, 5), and unfortunately you cannot add a single parameter containing the set of legal values there. Your best option is to either construct the SQL dynamically, or insert the values into a temporary table and do a join (or sub-select in the IN-clause). Commented Oct 21, 2013 at 8:05
  • 1
    Try SELECT FROM student WHERE ID IN (2,3,4) Commented Oct 21, 2013 at 8:06

8 Answers 8

8

Try this:

SELECT * FROM student WHERE ID IN (2,3,4)

Syntax:

test_expression IN 
    ( subquery | expression [ ,...n ]
    ) 

Read more about IN operator here.

Sign up to request clarification or add additional context in comments.

Comments

3

WHERE ID=2,3,4 and WHERE ID='2,3,4' are invalid syntax for SQL.

Looks like you can use IN (Transact-SQL) on your situation.

Determines whether a specified value matches any value in a subquery or a list.

SELECT FROM student WHERE ID IN (2, 3, 4)

Also you might take a look Jeff's question Parameterize an SQL IN clause

Comments

3

If you are passing @ID as a variable with comma separated list of ids, WHERE IN (@ID) will not work.

I think best thing would be to use a Table Valued function to split them first and then query the table. Please check here for a Split() function.

Usage:

SELECT * FROM STUDENT 
WHERE ID IN (
              SELECT items FROM dbo.Split(@ID, ',') --Split function here
            )

7 Comments

It is a simple one what is the use of Functions here Please check this out "Select Username from Student where ID IN ' + '('+ @Id +')'" where @Id=2,3,4 we can use like this
@Anjali: OP is using a stored procedure and not passing inline sql so It won't work unless you run a dynamic query.
Ok, but it work for stored procedures also i am using that query in stored procedures
Can you help me based on this. please come to chat
@Anjali: sure no problem, you can invite me.
|
2

If you want to fitler multiple values in Select, you should use "in ()":

SELECT * FROM student WHERE ID in (2,3,4)
OR
SELECT * FROM student WHERE ID between 2 and 4
OR
SELECT * FROM student WHERE ID = 2  OR ID = 3 OR ID = 4 

In this case take the first one. The last one is very slow and not recommended in this scenario.

Comments

2

Please check this out

Select * from Student where Id IN ('2','3','4')

and check this out

Select Username from Student where ID IN ' + '('+ @Id +')'
 where @Id=2,3,4

1 Comment

i understand the solution given should resolve my question but my ID column is of bigINT datatype and my @id variable is returned as string like {1,2,3} when i try concatenating the two i mean like SELECT * FROM students where ID IN @ID i get error because column ID is of BIGINT and i can't convert @ID to INT pls how do i go about this? You there?
2
Select * from Student where Id='2'
union all
Select * from Student where Id='3'
union all
Select * from Student where Id='4'

Comments

2

Based on your comment below, you don't want to convert ID to an int. Instead, use LIKE to compare:

SELECT * from STUDENT
WHERE ', '+@ID+', ' LIKE ', '+CAST(ID as NVARCHAR(255)) + ', ';

However, the query will not be indexed. If you want the query to be indexed, then use dynamic SQL:

DECLARE @query NVARCHAR(max) = 'SELECT * FROM STUDENT WHERE ID IN ('+ @ID +')';
EXEC sp_executesql @query;

1 Comment

i understand the solution given should resolve my question but my ID column is of bigINT datatype and my @id variable is returned as string like {1,2,3} when i try conactenating the two i mean like SELECT * FROM students where ID IN @ID i get error because column ID is of BIGINT and i can't convert @ID to INT pls how do i go about this? You there?
2

Since you are using Stored Procedure, that also has only equality compare i.e. id = 1, so either you have too execute three queries by splitting the input by comma separated values.

OR you can add a new procedure with a custom function to server with the SQL

CREATE FUNCTION dbo.myparameter_to_list (@parameter VARCHAR(500)) returns @myOutput TABLE (mytempVal VARCHAR(40))
AS  
begin
     DECLARE @TempTable table
          (
          mytempVal VARCHAR(40)
          )

     DECLARE @MySplittedValue varchar(40), @PositionOfComma int

     SET @par = LTRIM(RTRIM(@parameter))+ ','
     SET @PositionOfComma = CHARINDEX(',', @parameter, 1)

     IF REPLACE(@parameter, ',', '') <> ''
     BEGIN
          WHILE @PositionOfComma > 0
          BEGIN
               SET @MySplittedValue = LTRIM(RTRIM(LEFT(@par, @PositionOfComma - 1)))
               IF @MySplittedValue <> ''
               BEGIN
                    INSERT INTO @TempTable (mytempVal) VALUES (@MySplittedValue) --Use conversion if needed
               END
               SET @par = RIGHT(@par, LEN(@par) - @PositionOfComma)
               SET @PositionOfComma = CHARINDEX(',', @par, 1)

          END
     END    
     INSERT @myOutput
     SELECT mytempVal 
        FROM @TempTable
     RETURN
END       

In your stored procedure you would use it like this:

Create Procedure StudentSelectFromSet 
@Ids VARCHAR(MAX)
AS
SELECT * FROM student Stud
WHERE Stud.Id IN(SELECT value FROM dbo.myparameter_to_list (@Ids))

and then execute this new procedure as you were accessing earlier.

2 Comments

i understand the solution given should resolve my question but my ID column is of bigINT datatype and my @id variable is returned as string like {1,2,3} when i try concatenating the two i mean like SELECT * FROM students where ID IN @ID i get error because column ID is of BIGINT and i can't convert @ID to INT pls how do i go about this? You there?
@NuruSalihu hope new edited answer provides necessary solution to your query

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.