November 1, 2017 at 11:44 pm
I have a .net code which i need to replicate as it is in sql server. Need a same user defined function as follows. As I am not that much expert in sql server could you please help me.
My .net function is as follows.
public static string GetCsv(params string[] list) { string comma = ""; string ret = ""; for (int i = 0; i < list.Length; i++) { if (!string.IsNullOrEmpty(list)) { ret += comma + list; comma = ","; } } return ret; }
November 2, 2017 at 2:43 am
My C# isn't great, especially when code is given in one single (unreadable) line. My guess is that this is a Delimited String Splitter? If so, a simple Google Search would have yielded you a lot of results; there's even one on this site.
Thom~
Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
Larnu.uk
November 2, 2017 at 5:58 am
It doesn't split it creates a string from a list which each item separated by a comma. To do it in SQL check out the for xml options for concatenating strings - https://blog.sqlauthority.com/2009/11/25/sql-server-comma-separated-values-csv-from-table-column/
PS assuming you are using .net 4.0 then there is no need for a loop just use the following:
public static string GetCsv(params string[] list)
{
return string.Join(",", list);
}
November 2, 2017 at 6:09 am
Ahh, ok. If it's converting into a CSV then this will work (using STUFF and FOR XML PATH):
Thom~
Excuse my typos and sometimes awful grammar. My fingers work faster than my brain does.
Larnu.uk
November 2, 2017 at 7:22 am
Just adding more details as you got answers. You can't create a function that will work for everything, unless you do additional work that is not really recommended. You should understand how the XML concatenation works and Wayne Sheffield did a good job explaining it here: Creating a comma-separated list (SQL Spackle) - SQLServerCentral
Once you understood the process, you can simply create a snippet to speed up your coding. Or you can take the one I shared here among others:
http://www.sqlservercentral.com/articles/SSMS/138994/
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply