One reason of why I couldn't think of this solution before was my lack of knowledge in T-SQL. As I learn more and get comfortable with T-SQL, I realized it's power to do the stuff like that.
One book which really helped me to understand Microsoft SQL Server and T-SQL better is the Microsoft SQL Server 2012 T-SQL Fundamentals, one of the best books to learn T-SQL.
SQL Command to Convert Result of SELECT clause to CSV String
In order to collect result of SELECT clause in a comma separated String, you need to use a VARCHAR variable and concatenate each row by using that variable in SELECT clause using the COALESCE expression as shown below:DECLARE @csv VARCHAR(MAX) SELECT @csv = COALESCE(@csv + ',' ,'') + book_title from Test.dbo.Books where book_id IN ( 101, 102, 103); SELECT @csv Output Head First SQL, SQL Puzzler, T-SQL Fundamentals
This is a really nice tip and it had helped me a lot and, of course, saves effort and time too. You can use this whenever you need a comma separated list of values from a table. It's particularly useful when you output just one value from a table e.g. list of supported ids.
Here is one more example of creating a comma separated String from the result of SELECT clause in SQL, here we wanted names of all customer as CSV String.
As I said before, you can change the delimiter from comma to colon, pipe or anything else as well, just put what delimiter you want in the COALESCE expression. Here is an example of converting result of SELECT command to colon separated String.
That's all about how to convert the result of a SELECT command to comma separated String in SQL Server using T-SQL. Based upon this technique you can also come up with code for Oracle using PL/SQL and another database which allows variables. Once you know the trick there is no need to do double work of getting data from the database and then using a text editor to convert that list of values into a big CSV string. You can also change the delimiter and get a list of colon separated value or pipe delimited values.
No comments:
Post a Comment