I have a script as this:
Declare @Ids varchar = '1,2,3';
Select * from Table where Id in (@Ids)
How to separate or convert @Ids
into comma separated integers ?
Note: I don't want to create a new function for this.
I have a script as this:
Declare @Ids varchar = '1,2,3';
Select * from Table where Id in (@Ids)
How to separate or convert @Ids
into comma separated integers ?
Note: I don't want to create a new function for this.
It's not that pretty, and generally I put this in a function, but it works fine without one, if you already have a numbers table, you can skip the CTE, you can also get rid of the @delimiter
variable if you are always going to use a comma if you like:
DECLARE @ids VARCHAR(MAX) = '1,2,3';
DECLARE @delimiter VARCHAR(MAX) = ',';
WITH n AS ( SELECT x = ROW_NUMBER() OVER ( ORDER BY s1.[object_id] )
FROM sys.all_objects AS s1
CROSS JOIN sys.all_objects AS s2
CROSS JOIN sys.all_objects AS s3
)
SELECT *
FROM [table]
WHERE [Id] IN (
SELECT Item = SUBSTRING(@ids, x,
CHARINDEX(@delimiter, @ids + @delimiter,
x) - x)
FROM n
WHERE x <= CONVERT(INT, LEN(@ids))
AND SUBSTRING(@delimiter + @ids, x, LEN(@delimiter)) = @delimiter );