Skip to content

Instantly share code, notes, and snippets.

@somendra007
Created March 27, 2022 08:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save somendra007/99ceaa50a5a90bbb2734c199e2e96903 to your computer and use it in GitHub Desktop.
Save somendra007/99ceaa50a5a90bbb2734c199e2e96903 to your computer and use it in GitHub Desktop.
Create Split function in sql server
------------------------------------------------------------------
CREATED BY : SOMENDRA PRATAP SINGH
Date : 12 JUN 2013
PURPOSE : split deLimited text into rows / columns
select isnull(item, 0), * from Service.split1('', ' ', null)
select * from Service.split1('ram sham mohan rohan', ' ', null)
select * from dbo.split1('ram:23 sham:15 mohan:28 rohan:20', ' ', ':')
------------------------------------------------------------------
*/
CREATE function [dbo].[split1]
(
@str varchar(max), -- varchar change to 8000 from 1000 by saurabh gaur on 30/03/2006
@spliter char(1),
@colspliter char(1) = NULL
)
returns @tName table(item varchar(1000), item1 varchar(1000))
as
begin
declare @Substr as varchar(300),
@value1 as varchar(300),
@value2 as varchar(300),
@sql as varchar(500)
--If condition added by rahul on 15/10/2005
--to return null values if length of Input string is 0
if len(@str) = 0
begin
insert into @tName values(null, null)
return
end
--End of Condition added by rahul on 15/10/2005
if charindex(@spliter, @str, 0) <> 0
begin
while charindex(@spliter, @str, 0)<>0
begin
set @Substr=Substring(@str, 1, (charindex(@spliter, @str, 0)-1))
if charindex(@colspliter, @Substr, 0) <> 0 and @colspliter is not null
begin
set @value1 = Substring(@Substr, 1, (charindex(@colspliter, @Substr, 0)-1))
set @value2=Right(@Substr, len(@Substr)-(len(@value1)+1))
insert into @tName (item, item1) values (@value1, @value2)
end
else
insert into @tName (item) values (@Substr)
set @str=Right(@str, len(@str)-(len(@Substr)+1)) -- as spliter is of one char so +1 reduced
end
if @colspliter is not null --charindex(@str, @colspliter, 0) <> 0 and
begin
set @value1 = Substring(@str, 1, (charindex(@colspliter, @str, 0)-1))
set @value2=Right(@str, len(@str)-(len(@value1)+1))
insert into @tName (item, item1) values (@value1, @value2)
end
else
insert into @tName (item) values (@str)
end
else
begin
if @str is not null
BEGIN
if @colspliter is not null --charindex(@str, @colspliter, 0) <> 0 and
begin
set @value1 = Substring(@str, 1, (charindex(@colspliter, @str, 0)-1))
set @value2=Right(@str, len(@str)-(len(@value1)+1))
insert into @tName (item, item1) values (@value1, @value2)
end
else
insert into @tName (item) values (@str)
--insert into @tName (item) values (@str)
END
end
return
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment