Handy way of splitting comma separated values in T-SQL without using a function

I came across this situation wherein a need to split a comma separated value and insert it to the database, one by one. here's the solution to the problem.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
CREATE PROCEDURE ppm_InsertDealerContactsReportXref
 -- Add the parameters for the stored procedure here
 @dlrcxIddlrc INT = 0
 ,@dlrcxIdcl VARCHAR(300)
AS
BEGIN
 SET NOCOUNT ON;

 DELETE
 FROM dbo.rpm_DealerContactsReportXref
 WHERE dlrcxIddlrc = @dlrcxIddlrc

 DECLARE @DealerContactsReportXref TABLE (
  dlrcxIddlrc INT
  ,dlrcxIdcl VARCHAR(100)
  )

 INSERT INTO @DealerContactsReportXref (
  dlrcxIddlrc
  ,dlrcxIdcl
  )
 VALUES (
  @dlrcxIddlrc
  ,@dlrcxIdcl
  )

 INSERT INTO rpm_DealerContactsReportXref (
  dlrcxIddlrc
  ,dlrcxIdcl
  )
 SELECT dlrcxIddlrc
  ,LTRIM(RTRIM(m.n.value('.[1]', 'varchar(8000)'))) AS ids
 FROM (
  SELECT dlrcxIddlrc
   ,CAST('' + REPLACE(dlrcxIdcl, ',', '
') + '' AS XML) AS x
FROM @DealerContactsReportXref ) t CROSS APPLY x.nodes('/XMLRoot/RowData') m(n) SELECT @@ROWCOUNT END GO

Comments

Popular posts from this blog

Serializing JSON string to ExpandoObject

Adding an Obsolete Attribute to Class Methods in C#