0

I have this table structure and and some sample data. I want return data for multiple ids via parameter. I have declared a parameter string and now I want to compare it with the column but it ain't allowing because ID is integer. Can anybody give me any help here ?

CREATE TABLE EMPLOYEE
(
    ID INT,
    EMPLOYEE_NAME VARCHAR(50)
);

INSERT INTO EMPLOYEE VALUES (1, 'Isaac Frempong');
INSERT INTO EMPLOYEE VALUES (2, 'Eric Ortizz');

DECLARE @StrID VARCHAR(20) = '1, 2'
SELECT * FROM EMPLOYEE
WHERE ID = @StrID

5 Answers 5

1
SELECT * FROM EMPLOYEE
    WHERE @StrID+',' LIKE '%'+cast(ID as varchar(20))+'%,' 

Pretty bad performance as it will need to do a table scan but safe enough.

Generally though, your list of IDs should be a table variable you can do a proper JOIN or IN with

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

Comments

1

The easiest solution is to use dynamic SQL

DECLARE @sql VARCHAR(1000) = 'SELECT * FROM EMPLOYEE WHERE ID IN (' + @StrID + ')';
EXEC(@sql);

2 Comments

While it is simple indeed please bear in mind that this makes you vulnerable to SQL Injection attacks.
@MatthiasMeid Maybe, if it were open to outside users, this is entirely written by OP, so unless he wants to attack himself, he's safe :)
1

For SQL Server 2017+ you could use STRING_SPLIT a table-valued function that splits a string into rows of substrings

CREATE TABLE EMPLOYEE
(
ID INT,
EMPLOYEE_NAME VARCHAR(50)
);

INSERT INTO EMPLOYEE VALUES (1, 'Isaac Frempong');
INSERT INTO EMPLOYEE VALUES (2, 'Eric Ortizz');

DECLARE @StrID VARCHAR(20) = '1, 2'
SELECT * FROM EMPLOYEE
WHERE ID IN (SELECT value FROM STRING_SPLIT (@StrID,','))

Refer this working fiddle

Comments

1

Create a user defined table type and pass it as a parameter.

CREATE TYPE [UDT_INTIDS] AS TABLE(
    [ID] [int] NOT NULL
)
GO

-- create a table value
DECLARE @IDs [UDT_INTIDS];
INSERT @IDs VALUES (1),(2);

-- search using table value. 
SELECT e.* 
FROM EMPLOYEE e
WHERE e.ID IN (SELECT p.ID FROM @IDs p);
-- or
SELECT e.* 
FROM EMPLOYEE e
JOIN @IDs p ON e.ID = p.ID;

See https://learn.microsoft.com/en-us/sql/relational-databases/tables/use-table-valued-parameters-database-engine?view=sql-server-2017 for more details.

Comments

0

You can use the Cast in SQL-Server to cast it to the appropriate datatype. Source Here

WHERE CAST(ID AS VARCHAR(20)) = @StrID

Alternatively: You can use CONVERT function.

WHERE CONVERT(VARCHAR(20), ID) = @StrID

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.