Go Premium for a chance to win a PS4. Enter to Win

x
Solved

# Split in SQL Server

Posted on 2011-02-11
Medium Priority
254 Views
I have values in a variable(term) as (2004,2005,2006,....2011). I would like to split the term into individual year and store in another variable say X.

0
Question by:cimscims
• 2

LVL 61

Accepted Solution

HainKurt earned 2000 total points
ID: 34872864
use this functions, then

select dbo.splitNGet('2004,2005,2006,2011',3,',')

to get the third element...
``````CREATE FUNCTION [dbo].[fnSplit](
@sInputList VARCHAR(8000), -- List of delimited items
@sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
) RETURNS @List TABLE (n int, item VARCHAR(8000))
BEGIN
DECLARE @sItem VARCHAR(8000);
DECLARE @sRow int = 1;

WHILE CHARINDEX(@sDelimiter,@sInputList,0) <> 0
BEGIN
SELECT
@sItem=RTRIM(LTRIM(SUBSTRING(@sInputList,1,CHARINDEX(@sDelimiter,@sInputList,0)-1))),
@sInputList=RTRIM(LTRIM(SUBSTRING(@sInputList,CHARINDEX(@sDelimiter,@sInputList,0)+LEN(@sDelimiter),LEN(@sInputList))))
IF LEN(@sItem) > 0
INSERT INTO @List SELECT @sRow, @sItem
set @sRow = @sRow + 1;
END
IF LEN(@sInputList) > 0 INSERT INTO @List SELECT @sRow, @sInputList -- Put the last item in
RETURN
END;

CREATE function [dbo].[splitNGet](
@sInputList VARCHAR(8000), -- List of delimited items
@n int,
@sDelimiter VARCHAR(8000) = ',' -- delimiter that separates items
)RETURNS varchar(8000)
begin
declare @item varchar(8000);

select @item = item from dbo.fnSplit(@sInputList, @sDelimiter)
where n=@n;

return @item;
end;
``````
0

LVL 61

Expert Comment

ID: 34872897
or you can use

select * from dbo.fnSplit('2004,2005,2006,2011',',')

1      2004
2      2005
3      2006
4      2011

select dbo.splitNGet('2004,2005,2006,2011',3,',')

2006
0

Author Closing Comment

ID: 34872965
It worked.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have a large data set and a SSIS package. How can I load this file in multi threading?
Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…
###### Suggested Courses
Course of the Month12 days, 2 hours left to enroll