1

Here is my table named Employee

-----------------------
Column Name | Data Type
----------------------
ID          | int
EmpId       | nvarchar
Name        | nvarchar
Salary      | decimal

Have a look all the records of the table

------------------------------
ID | EmpId |  Name   |  Salary
------------------------------
1  | 200   |  Bulbul | 2000.00
2  | 201   |  Ahmed  | 2000.00
3  | 202   |  Rakib  | 2500.00
4  | 203   |  Rubel  | 3000.00
5  | 204   |  Zia    | 4000.00

Now if I want get all the records of a given employee id to the IN operator, I get the following result. It's just fine.

SELECT EmpId, Name, Salary
FROM Employee
WHERE EmpId IN ('200','201')

------------------------------
ID | EmpId |  Name   |  Salary
------------------------------
1  | 200   |  Bulbul | 2000.00
2  | 201   |  Ahmed  | 2000.00

But if I pass the employee id as parameter, then I don't get my desired results. Just get empty result.

DECLARE @Params AS NVARCHAR(MAX) = '''200'',''201'''

SELECT EmpId, Name, Salary
FROM Employee
WHERE EmpId IN (@Params)  

------------------------------
ID | EmpId |  Name   |  Salary
------------------------------
   |       |         |  
   |       |         |  

Now I need to get the following result using parameter in IN operator. My desired result is something like:

------------------------------
ID | EmpId |  Name   |  Salary
------------------------------
1  | 200   |  Bulbul | 2000.00
2  | 201   |  Ahmed  | 2000.00

Please help me to get my desire result. Thank in advance.

1
  • 1
    What version of SQL Server? Commented Aug 26, 2014 at 5:31

4 Answers 4

4

I suggest that use Table Type Parameter.

CREATE TYPE dbo.IdList AS TABLE (Id INT)
GO

DECLARE @Ids dbo.IdList 

INSERT INTO @Ids(Id)VALUES(200),(201)

SELECT EmpId, Name, Salary
FROM Employee
WHERE EmpId IN (SELECT Id FROM @Ids)
Sign up to request clarification or add additional context in comments.

4 Comments

Getting an error Msg 102, Level 15, State 1, Line 2 Incorrect syntax near 'READONLY'.
Drop READONLY and make sure to insert into @Ids and it works just fine. And never, ever, say "getting an error" or the equivalent, always post the exact error message you get.
@Lasse V Karlsen. Tanks For your comment.
@NEO. I correct my answer. It's execute without any error.
1

Add below Table valued SQL Function fn_split:

CREATE FUNCTION [dbo].[fn_Split](@sText varchar(8000), @sDelim varchar(20) = ' ')
RETURNS @retArray TABLE (idx smallint Primary Key, value varchar(8000))
AS
BEGIN
DECLARE @idx smallint,
    @value varchar(8000),
    @bcontinue bit,
    @iStrike smallint,
    @iDelimlength tinyint

IF @sDelim = 'Space'
    BEGIN
    SET @sDelim = ' '
    END

SET @idx = 0
SET @sText = LTrim(RTrim(@sText))
SET @iDelimlength = DATALENGTH(@sDelim)
SET @bcontinue = 1

IF NOT ((@iDelimlength = 0) or (@sDelim = 'Empty'))
    BEGIN
    WHILE @bcontinue = 1
        BEGIN

--If you can find the delimiter in the text, retrieve the first element and
--insert it with its index into the return table.

        IF CHARINDEX(@sDelim, @sText)>0
            BEGIN
            SET @value = SUBSTRING(@sText,1, CHARINDEX(@sDelim,@sText)-1)
                BEGIN
                INSERT @retArray (idx, value)
                VALUES (@idx, @value)
                END

--Trim the element and its delimiter from the front of the string.
            --Increment the index and loop.
SET @iStrike = DATALENGTH(@value) + @iDelimlength
            SET @idx = @idx + 1
            SET @sText = LTrim(Right(@sText,DATALENGTH(@sText) - @iStrike))

            END
        ELSE
            BEGIN
--If you can’t find the delimiter in the text, @sText is the last value in
--@retArray.
 SET @value = @sText
                BEGIN
                INSERT @retArray (idx, value)
                VALUES (@idx, @value)
                END
            --Exit the WHILE loop.
SET @bcontinue = 0
            END
        END
    END
ELSE
    BEGIN
    WHILE @bcontinue=1
        BEGIN
        --If the delimiter is an empty string, check for remaining text
        --instead of a delimiter. Insert the first character into the
        --retArray table. Trim the character from the front of the string.
--Increment the index and loop.
        IF DATALENGTH(@sText)>1
            BEGIN
            SET @value = SUBSTRING(@sText,1,1)
                BEGIN
                INSERT @retArray (idx, value)
                VALUES (@idx, @value)
                END
            SET @idx = @idx+1
            SET @sText = SUBSTRING(@sText,2,DATALENGTH(@sText)-1)

            END
        ELSE
            BEGIN
            --One character remains.
            --Insert the character, and exit the WHILE loop.
            INSERT @retArray (idx, value)
            VALUES (@idx, @sText)
            SET @bcontinue = 0  
            END
    END

END

RETURN
END

And execute this query to get your output:

DECLARE @Params AS NVARCHAR(MAX) = '200,201'
SELECT EmployeeId, Name
FROM Employee
WHERE EmployeeId IN (select value from dbo.fn_Split(@Params,','))

Hope this helps!

1 Comment

This solution didn't help? Why you voted down? I've checked it and it is working fine with your expected output in a statement query with optimized way in light weight execution plan?
0

Please try:

DECLARE @Params AS NVARCHAR(MAX) = '200,201'

exec ('SELECT EmpId, Name, Salary
       FROM Employee
       WHERE EmpId IN ('+@Params+')')

3 Comments

If you are sure that sql injection not a problem,. i would say this is best answer. this query will be optimal as can use statistics. but well recompile all the time whenever call. PS. this comment from just performance point of view.
-1 Because dynamic query execution is always slower and to be avoided at all costs.
Yep. Read up on execution plans and SQL injection attacks. Writing code that uses dynamic SQL is not a good idea.
0

Finally I got my expected result doing something like:

CREATE TABLE #EmpTable
(
  EmpId NVARCHAR (50) NULL
)
GO
DECLARE @Parameter AS NVARCHAR(MAX) = '(''201''),(''202'')'
DECLARE @SQL AS NVARCHAR(MAX) ='INSERT INTO #EmpTable (EmpId)VALUES' + @Parameter
EXEC (@SQL)
GO
SELECT EmpId, Name, Salary
FROM Employee
WHERE EmpId IN (SELECT EmpId FROM #EmpTable)

Comments

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.