Skip to content

Instantly share code, notes, and snippets.

@JonathanLoscalzo
Created June 6, 2018 13:46
Show Gist options
  • Save JonathanLoscalzo/0d5e4a7182526b49a5bf8bdf59fef758 to your computer and use it in GitHub Desktop.
Save JonathanLoscalzo/0d5e4a7182526b49a5bf8bdf59fef758 to your computer and use it in GitHub Desktop.
how to split comma parameters in sql
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[Split]
(
@String NVARCHAR(4000),
@Delimiter NCHAR(1)
)
RETURNS TABLE
AS
RETURN
(
WITH Split(stpos,endpos)
AS(
SELECT 0 AS stpos, CHARINDEX(@Delimiter,@String) AS endpos
UNION ALL
SELECT endpos+1, CHARINDEX(@Delimiter,@String,endpos+1)
FROM Split
WHERE endpos > 0
)
SELECT 'Id' = ROW_NUMBER() OVER (ORDER BY (SELECT 1)),
'Data' = SUBSTRING(@String,stpos,COALESCE(NULLIF(endpos,0),LEN(@String)+1)-stpos)
FROM Split
)
DECLARE @list VARCHAR(MAX) = '12,13,15,18,19,102';
Create TABLE #TEMPORAL_TABLE ( id_temp INT )
Insert #SUSCRIPCIONES ( id_temp )
Select Data From dbo.Split( @list, ',' ) -- it's a function, it returns like a table
-- example 1
DELETE FROM dbo.my_example_table WHERE id IN (SELECT * FROM #TEMPORAL_TABLE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment