How to convert a string with multiple comma separated values to rows in SQL Server
Let’s we have below table structure: create table Testdata ( SomeID int , OtherID int , Data varchar ( max ) ) This table contain below sample records insert Testdata select 1 , 9 , '18,20,22' insert Testdata select 2 , 8 , '17,19' insert Testdata select 3 , 7 , '13,19,20' insert Testdata select 4 , 6 , '' We want to get result like 1 9 18 1 9 20 1 9 22 2 8 17…. We can use below two options for this problem. Using function and table variable CREATE FUNCTION dbo . Split ( @Line nvarchar ( MAX ), @SplitOn nvarchar ( 5 ) = ',' ) RETURNS @RtnValue table ( Id INT NOT NULL IDENTITY ( 1 , 1 ) PRIMARY KEY CLUSTERED , Data nvarchar ( 100 ) NOT NULL ) AS BEGIN IF @Line IS NULL RETURN DECLARE @split_on_len INT = LEN ( @SplitOn ) ...