SQL Server - Equivalent split function

Asked By Umair Imran
04-Mar-08 05:06 AM

I have a comma seperated value in a varchar(4000) variable
I have to get it one by one and use it
How can i do it?
e.g.

DECLARE @str varchar(4000) = 'Item1, Item2, Item3, Item4'
1.   SET @item_id = Get fist comma value from @str i.e. Item1
2.      SELECT @item_name = @item_name + Table1.Item_Name 
         FROM Table1 
         WHERE Table1.Item_Id = @item_id
3.   GO to Step 2 until all comma seperated values are parsed.

Thnx in advance

Equivalent split function  Equivalent split function

04-Mar-08 05:22 AM

try out this function to get the comma seperated string in the form of table and iterate it in the loop to get each value

FUNCTION getstringintableform (tempstr IN VARCHAR2, separator IN CHAR)

RETURN getstringintableform_temptab

IS

temp getstringintableform_tempobj;

tempstr_ VARCHAR2 (32000) := tempstr;

separator_ CHAR (1) := separator;

separator_position NUMBER (10, 0);

tmptab getstringintableform_temptab

:= getstringintableform_temptab

();

BEGIN

tempstr_ := tempstr_ || separator_;

separator_position := INSTR (tempstr_, separator_);

WHILE separator_position <> 0

LOOP

temp := getstringintableform_tempobj (NULL);

temp.col1 := TRIM (SUBSTR (tempstr_, 1, separator_position - 1));

tempstr_ := SUBSTR (tempstr_, separator_position + 1);

separator_position := INSTR (tempstr_, separator_);

tmptab.EXTEND;

tmptab (tmptab.COUNT) := temp;

END LOOP;

RETURN tmptab;

END getstringintableform;

 

Its in oracle, convert to sqlserver code...

 

parsing the comma seperated values  parsing the comma seperated values

04-Mar-08 05:26 AM

try the below code,

DECLARE @OrderList varchar(4000)
DECLARE @OrderID varchar(10), @Pos int

 SET @OrderList = 'Item1, Item2, Item3, Item4'

 SET @OrderList = LTRIM(RTRIM(@OrderList))+ ','
 SET @Pos = CHARINDEX(',', @OrderList, 1)

 IF REPLACE(@OrderList, ',', '') <> ''
 BEGIN
  WHILE @Pos > 0
  BEGIN
   SET @OrderID = LTRIM(RTRIM(LEFT(@OrderList, @Pos - 1)))
   IF @OrderID <> ''
   BEGIN
    --the below statement will display the values one by one , you can manipulate the value here however you want
    SELECT @OrderID
   END
   SET @OrderList = RIGHT(@OrderList, LEN(@OrderList) - @Pos)
   SET @Pos = CHARINDEX(',', @OrderList, 1)

  END
 END 

I took the code from a site and modified it a bit, hope it helps! you can get lot of sample snippets when you google for it, just FYI.

Comma Delimited Value to Table  Comma Delimited Value to Table

04-Mar-08 09:44 AM

You can also convert your comma-separated value into a table using the function described in the following link:

http://www.sql-server-helper.com/functions/comma-delimited-to-table.aspx

With a table, you can easily do a join with other tables instead of processing your values one at a time.

One Question  One Question
04-Mar-08 11:07 PM

IF REPLACE(@OrderList, ',', '') <> ''

Can you tell me what this line doing here?
Is All the commas in @OrderList replaced by empty string.

Some time before I use this code with few changes but don't use this line and the code worked well.

comma value alone  comma value alone
05-Mar-08 04:36 AM
incase if your @OrderList variable just contains the value comma (,) then we dont have to process it, thats why they are checking this IF Condition which will return '' in this case.
thnx  thnx
05-Mar-08 06:53 AM
end of post
Comma Seperated Values  Comma Seperated Values
05-Mar-08 06:57 AM

Hello There,

Try this , I hope it helps

Select identity(int,1,1) seq into Numbers from sys.sysobjects t ,sys.sysobjects t1

Select SUBSTRING( Names, n.seq, CHARINDEX( ',', names + ',', n.seq ) - n.seq )

from ( Select 'jatinder,raj,rajinder' Names ) XY, Numbers n

where SubString(','+Names,n.seq,1) = ',' and n.seq<len(XY.Names)

The condition of  n.seq<len(XY.Names) is there to check only ',' equal to length of string to be parsed.

 

With Warm regards

Jatinder Singh

http://jatindersingh.blogspot.com

 

 

Create New Account
help
Fill(ds, “Products”) DataGrid1.DataSource = ds.Tables(”Products”) What is the maximum length of a varchar in SQL Server? Answer1 VARCHAR[(n)] Null-terminated Unicode character string of length n, with a maximum of 255 characters The presentation logic is done with .aspx extention. How do you define an integer in SQL Server? We define integer in Sql server as var_name int How do you separate business logic while creating an ASP.NET application
date time format hi, I want to retrieve the date from sql server to dot net, but i want that in dd / mm / yyyy format.actually i have taken the date time datatype in sql server.but i want only dd / mm / yyyy.in front end when i retrieve from database time, pls help me as early as possible SELECT TOP 1 ID, Start_Date, 3 > CONVERT ( varchar, Start_Date, 100 ) 'Mm m dd yyyy hh:mmdp ', 4 > CONVERT ( varchar, Start_Date, 101 ) 'mm / dd / yyyy ', 5 > CONVE ( varchar, Start_Date, 103 ) 'dd / mm / yyyy ' / / Your required format 6 > FROM Employee You can Use CONVERT in your SQL query to convert it into your format; CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) See this link
a parameter value is not supplied it is set to NULL. CREATE PROCEDURE ps_Customers_SELECT_NameCityCountry @Cus_Name varchar(30) = NULL, @Cus_City varchar(30) = NULL, @Cus_Country varchar(30) = NULL AS SELECT Cus_Name, Cus_City, Cus_Country FROM Customers WHERE Cus_Name = COALESCE(@Cus_Name, Cus_Name) AND there and I'm searching data using storeprocedure. . . . So, I have to do all in sql server. . . . Is there any way to do this in sql server.??? you need to use split paramter with ' \ ' to getting all value and than add all one using like search and finaly you can use that serach with where clause of sql query WHILE @i < = @MaxID BEGIN SET @Search = @Search + ', colname like (%' + CONVERT ( VARCHAR (10), @splitValue) + '%)' SET
the CSS script mentioned below in Head section of html source of page < head runat = "server" > < title > Progress Image in AutoComplete TextBox < / title > < style > .AutoExtender { font-family: Verdana, Helvetica, sans-serif weight: normal; border: solid 1px #006699; line-height: 20px; padding: 10px; background-color: White; margin-left:10px; } .AutoExtenderList { border-bottom: dotted 1px #006699; cursor: pointer; color: Maroon; } .AutoExtenderHighlight { color: White; background The complete html source of AutoComplete Extender will look like < asp:TextBox ID = "txtAutoComplete" runat = "server" Width = "252px" > < / asp:TextBox > < div ID = "divwidth" > < / div > < ajaxToolkit:AutoCompleteExtender runat = "server" ID = "AutoComplete1" BehaviorID = "autoComplete" TargetControlID = "txtAutoComplete" ServicePath = "AutoComplete.asmx" ServiceMethod = "GetCompletionList" MinimumPrefixLength = "1" CompletionInterval = "10 you will not need to do that. Right. :-) ? [WebMethod] public string [] GetUsers( string prefixText, int count ) { List< string > names = new List< string > () { "Alpha" , "Beta" , "Gamma" , "Delta" , "Omega" }; / / Fake delay to see web service we have created and it will be using. ? < asp:ScriptManager ID = "ScriptManager1" runat = "server" EnablePartialRendering = "true" > < Services > < asp:ServiceReference Path = "~ / AjaxServices.asmx" / > < / Services > < / asp:ScriptManager > • Add three more controls your system. ? < table > < tr > < td > User:&nbsp;&nbsp;< / td > < td > < asp:TextBox ID = "tbUser" runat = "server" > < / asp:TextBox > < / td > < td > &nbsp;< / td > < td > < img id = "processing" style = "visibility:hidden" src = "ajax-loader.gif" / > < / td > < td > &nbsp;< / td > < td > < cc1:AutoCompleteExtender ID = "AutoCompleteExtender1" runat = "server" TargetControlID = "tbUser" ServicePath = "AjaxServices.asmx" ServiceMethod = "GetUsers" MinimumPrefixLength = "1" EnableCaching = "true" CompletionSetCount = "25" onclientpopulating = "ShowIcon
between two characters in TSQL Hello, I am trying to pull data out of a Varchar field that is surrounded by Chr(13). This data can sometimes have a period or comma in it so using something like PARSENAME(REPLACE(defendant_info, CHAR(13)+Char(10), '.'), 2) AS defAdd will not work. Any ideas on how to pull that data l_name, combined_name, Court, plaintiff_info, JDate, defendant_info, revived_date, JAmt, DSN, CaseID, DocketTypeCode, jh_id, tdef_id, biannual_mainframe_id, excluded, LEFT (defendant_info, CASE WHEN CHARINDEX(CHAR(13), defendant_info)> 0 THEN CHARINDEX(CHAR(13), defendant_info) -1 ELSE LEN(defendant_info) END) AS def, defAdd, RIGHT (defendant_info, 5) AS defZip, LEFT (defendant_info, CASE WHEN CHARINDEX CHAR(13), plaintiff_info)> 0 THEN CHARINDEX(CHAR(13), plaintiff_info) -1 ELSE LEN(plaintiff_info) END) AS tiff