Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server / SQL-Server-2014

How to Split Microsoft SQL Server Table Row Data

5.00/5 (5 votes)
18 Dec 2015CPOL 10.7K  
This tip shows you an easy way to split Microsoft SQL Server table row data.

Introduction

This tip shows you an easy way to split Microsoft SQL Server table row data.

Using the Code

A sample code snippet is given below:

SQL
-- SELECT @tableColumnID, Data  FROM dbo.[FUN_split_row_data](@p_row_string_data,',')
CREATE FUNCTION [dbo].[FUN_split_row_data]
(
	@p_row_data NVARCHAR(2000),
	@p_split_on NVARCHAR(256)
)  
RETURNS @g_ret_value TABLE 
(
	id INT idENTITY(1,1),
	data nvarchar(100)
) 
AS  
BEGIN 
	DECLARE @g_counter INT
	SET @g_counter = 1

	WHILE (CHARINDEX(@p_split_on,@p_row_data)>0)
	BEGIN
		INSERT INTO @g_ret_value (data)
		SELECT data = LTRIM(RTRIM(SUBSTRING(@p_row_data,1,CHARINDEX(@p_split_on,@p_row_data)-1)))

		SET @p_row_data = SUBSTRING(@p_row_data,CHARINDEX(@p_split_on,@p_row_data)+1,LEN(@p_row_data))
		SET @g_counter = @g_counter + 1
	END
	
	INSERT INTO @g_ret_value (data)
	SELECT data = LTRIM(RTRIM(@p_row_data))

	RETURN

END

Input

SQL
SELECT  1234 AS id, data  FROM dbo.[FUN_split_row_data]_
('Hello,world,!!!,you are, most, welcome, at, codeproject.com',',') 

Output

id    data

------------------
314    Hello
314    world
314    !!!
314    you are
314    most
314    welcome
314    at
314    codeproject.com

Conclusion

I hope you guys get the scenario and this might be helpful to you. Enjoy!

History

  • Saturday, December 19th, 2015: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)