Sql Server does not (on my knowledge) have in-build Split function.
Split function in general on all platforms would have comma-separated string value to be split into individual strings.
In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.
The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.
CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
split function can be Used as
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')
would return
Above Split function can be used to pass parameter to IN clause in sql server.
Thanks for the function man, works like a charm.
thanks very muck it was very handy
I am using your Split function. It works great. Can you tell me, How to store those splitted values into the database table. I am using insert statement. It is giving error. May be I am using in a wrong way. Can you please tell me how to insert them into the table?
ratna,
create table #temptable (id int identity(1,1),col1 varchar(255))
insert into #temptable
select * from dbo.split('Chennai,Bangalore,Mumbai',',')
select * from #temptable
Thanks for this inspiring code. I have modified it to also be used as a scalar function. Tried to submit the modified code but your website does not allow its submission. Will be glad to submit the modified version if requested.
Hey have been looking for such a thing for a long time now, but may i use this on an already exiting table, where most the coloum are with ; and , seperated data.... Can you help please
Great function and it helped very well. But what if the input string length exceeds 8000?
whn i execute Select dbo.Split('1,2,3,4',',') it give me following error:: Msg 4121, Level 16, State 1, Line 2 Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Split", or the name is ambiguous. y so?
Working fine and very help where we generally use in option in procedure. we can use this function... thanks lot.
As stated by Riya, I have a table containing delimited data that we need to split into multiple rows. One way is to create a cursor and loop thru all rows. Anyone know of a more efficient method?
Thank you-- saved me a lot of time on an already lengthy task!
i have a table, and there is a column which has a string value asdfadf,zcvzcv how do i run this function against the table column? something like this? select * from [mydatabase].[dbo].[split] (mycolumn, ',') just wondering.
Hey, thanks. Works like a chard
thanks........
Great function and it helped very well
If the last character in the string is a space, it fails to parse correctly. DECLARE @String SET @String = 'IMM,CE ,CM ' SELECT * FROM dbo.split(@string,',') RESULTS: IMM E M
Changing the LEN function to DATALENGH should correct the problem with trailing spaces.
This just saved my life. Thanks!
hai Thank u very much
Hi, I want to apply this function to one of my table in the database, how can I do that? e.g If in a search box, I put keywords like "sql,java" then it should give those results which have either "sql" or "java" or both, in the skill sets. "Skill set" is a column name in the table. Please resolve this problem.. Thanks.
u r great man.i like it
Great and simple example . It works good. Complete solution for the task.
How we can achieve the same without using that function(I need to use only SQL query). Thanks in advace.
There are two tables "germanytable2" and "thridfile". following are the columns each table has : "germanytable2": bpcustname,countryname,groupid etc. "thridfile": tradingname,country,id etc. task: get all those id's from "thirdfile" if the condition tradingname=bpcustname. logic i thought of: first will do the exact match like: //select a.bpcustname,a.groupid,a.countryname,b.tradingname,b.id from germanytable2 as a join thirdfile as b on a.bpcustname = b.tradingname// **there are 10334 matches. now i want to put these matches aside and compare from those which are notmatched with soundex function.** if i compare directly wid soundex its giving me enormous results..so jus want to compare from the remaining. here logic : create a table wid columns like groupid,bpcustname,country,match from both the old tables "germanytable2" and "thirdfile" code: select bpcustname,groupid,countryname into germany_newtable from germanytable2 select id,tradingname,country,match into thirdfile_newfile from thirdfile will go to design part and add other columns called "match" for both the newly created tables. then the code goes as follows: select a.groupid, a.bpcustname, a.countryname, a.match, b.tradingname, b.id, b.country, case when a.bpcustname = b.tradingname then 'y' END 'Category' from germany_newtable as a join thirdfile_newfile as b on a.bpcustname = b.tradingname. now i want to update the match column to 'y' and perform the same using soundex function for the remaining data using the conditions soundex(a.bpcustname) = soundex(b.tradingname) and match != y. hope it is little clear and need some help in this regard.
I Have Three Strings like 'New Inc., Family Academy' 'ABC Company' 'XYZ Organization' how to use the above function to make use of it?
Thanks.But how to split a string using different operators.(ex: A+B-C/D) Is it possible to split '+,-,/' wise.
Thank you, this split function was exactly what I needed. Can't believe that something like this is not built-in.
Hi Thank u very much,This good,but I have a table containing delimited data that we need to split into multiple rows. And Use this function.please tell me how ca i do that
declare @str varchar(100) set @str=( select * from details) insert into #temptable select * from split(@str,',') select * from #temptable I get only the first value. Why? Can any one help? details table has one record '111,222,333,444,555'
Very useful function. Thanks.
I am trying to write a fucntion to do this. However havign no solution yet after 4 hour of work, I am trying to split a String into Row and Column "A_B_C,D_E_F" Into A B C D E F Thanks
Check this out for the same: http://praveenbattula.blogspot.com/2010/06/best-split-udf-function-with-delimeter.html
thank u so much..it has helped me a lot
Great function! You have helped out a lot of people, keep up the good work!
Thanks for this stuff.
This function helped me lots. Thanks.
Awsome, It really helps. Thanks for sharing! Blessings to you!
Thank you so much Really help me
Great code snippet!! Thanks for sharing.
I have a table like below and I wan to seperate the comma values and get distinct values from them slno WFTools ----- ----------- 1 EMEA-OVSC, OVSD 2 EMEA-OVSC, Radix 3 Radix 4 OVSD, Dav, MR and I want EMEA-OVSC Radix OVSD Dav MR can some one help on this?
Thank u.............................
This is a very good code snippet. Mant thanks for sharing. It works like a charm
Adress Chennai,Tamil Nadu,India i need output as below City State Country > These are Meta Data Chennai Tamil Nadu India This is data
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',') The above is not right... Try the following,I hope that It may help you. select * from [dbo].[UDF_SPLIT]('Chennai,Bangalore,Mumbai',',')
Thanks a lot!!!!!!!!!! This function is really so helpful for me :)
Great function! But i have a problem, i m using sql server 2000, when string length exceeds 4000 it retrieve an error: Implicit conversion from data type ntext to varchar is not allowed. Use the CONVERT function to run this query. Any ideias?
good one... http://www.a2zmenu.com/MySql/SQL-Split-Function.aspx
Thanks! It worked really well!
Thanks alot. The function works very well. Cheers
select * from dbo.SPLIT(@donationtype,'~'),dbo.SPLIT(@amount,'~') i want to use multiple split fucntion in select statement please help me
Thanks...it worked in a single shot!!
Done a mavelous job.
How do I store return string values in different columns including null values, example, String: ABC,DEF,,,DGG,SS,,, colum1 column2 column3 etc...
Such a perfect piece of sql! Used in a complex query to give users ability to search a dateTime field by year, month/year, full date combination, and your function along with a scroll cursor worked just beautifully.
You just saved my butt... thanks so much!
thanks
Thanks a lot! This is what i search for!
Brilliant function, many thanks indeed, helped me a great deal.
check this also: http://chamilaw.blogspot.com/2011/05/concatenation-in-select-and-split.html
I need to convert this MS SQL Function into My SQL. n How to use it. I will be great full is someone helps me pls. Its URGENT.
Thanks a lot. You made my day. I have book marked this site.
Ggreat example. Thank you for your post
Thanks. it was help
SELECT PARSENAME(REPLACE('Hello RAJ SATRE', ' ', '.'), 3) --return Hello
Big help, thank you!
Thank you for this very informative blog. The function is very simple and has helped me BIG TIME. Will bookmarked this site and wait for updates.
thank you! very much
Nice.. Its working perfect
Thanks it works great :-)
thnx frnd....
sir u have given me this snippet sir its useful but i want it to be used in a existing table i dono how to use it sir kindly guide me sir thanking u
Cool Man.... Very Good Programming.....
how can i conver this function to display strings in sperate columns . like converting string(name1, name, name3) into seperate columns name1 name2 name3
Thanks a lot for sharing :) God bless you
Muchas gracias por compartir!!
Thanks for sharing! but select top 10 * from dbo.split(N'5,4,8, 9 ',',') didn't return the right result
wow just what i need
Excellent function. Very useful
How to call this split function in stored procedure for store multiple data in table ?
Thank you, I have been looking for a function to do this Instead of using CURSOR and FETCH to manually and tediously read every comma in the account number , I used this function. Thank you very much...
Can U please write or convert the same Split function in MYSQL.
Hope I am not very late to the party :) Just thought of posting the link of my blog post relating to this topic. http://vadivel.blogspot.com/2011/10/how-to-split-delimited-string-values-in.html Hope it would be of help to somebody someday :)
I am using the above written query, but not getting the desired result.Plss help me
Thanks a lot for this wonderful function! Really helped me solve my problem...
Thank you very much.. I had headache for that... now I got it.. declare @StringValue varchar(50) set @StringValue = (select authors from tbl_book where book_id='B0002' ) select top 10 * from dbo.split(@StringValue,',')
Muchas gracias por tu aporte, thanks!!!
Thanks a lots! .Really superb function.
I wani to use this function in table i am using select * from dbo.split(select cuisines from restaurant,',') but its not working Here cuisines column contains comma separated values. How i can get this??? Please Help!!
I got my solution select b.items as splitvalue from restaurants_details a cross apply dbo.fun_Split(a.cuisines,',') b
Thank you ver much. Your code is a very important contribution for the programmers
That was helpful, thanks. I specially liked the idea of delimiter. This way, your function is not an ad-hoc CSV separator, and can turn any delimitted-string into an array of tokens. Great.
Thank you for the function. I'm fairly new to SQL and this save me a bunch of time. It allowed me to concentrate on the core of my project :)
Great !! this function is usefull, as i was searchng Thanks bro !!
Hi all i want to "con cat" all columns in a single line please use procedure with "loop "
Thank you very much for sharing this awesone function.
Thanks a lot
Thank you for this handy function. Saved me a few hours. It works great!
CHANGE: insert into @temptable(Items) values(@slice) TO : insert into @temptable(Items) values(LTRIM(RTRIM(@slice))) To get rid of spaces if you do: A, B, C instead of A,B,C Thanks,
Thank you so much! Heaven Sent!
Thank you very much, I'm a new employee in a developpent socity and your function is a big solution for a big problem that I have recently. Thanks
Hi, Nice & very helpful article, I recently did the development of the same function via XQuery. http://raresql.com/2012/02/14/split-function-in-sql-server/ Imran
Works great! Really helped me. MS SQL should make this as inbuild funtion...
superb query. Main thing is here nothing is hardcoded. Keep it up
Great code, saved me a lot of work. Thanks a lot!
Excellent utility
Thanks a lot!!!!
Thanks for sharing!
YEAH BABY !~~~~ THANKS!