How to split string containing matrix into table in SQL Server? String has columns and row delimiters.
Suppose I have a string:
declare @str varchar(max)='A,B,C;D,E,F;X,Y,Z';
Expected results (in three separate columns):
+---+---+---+
| A | B | C |
+---+---+---+
| D | E | F |
+---+---+---+
| X | Y | Z |
+---+---+---+
I am looking for general solution which has not defined number of columns and rows. So the string:
declare @str varchar(max)='A,B;D,E';
will be split into table with two columns:
+---+---+
| A | B |
+---+---+
| D | E |
+---+---+
My efforts. My first idea was to use dynamic SQL which turns the string into:
insert into dbo.temp values (...)
This approach although very fast has a minor drawback because it requires creating a table with the right number of columns first. I have presented this method in the answer to my own question below just to keep the question short.
Another idea would be to write down the string to a CSV file on the server and then bulk insert
from it. Though I do not know how to do it and what would be performance of first and second idea.
The reason why I asked the question is because I want to import data from Excel to SQL Server. As I have experimented with different ADO approaches, this method of sending matrix-string is a landslide victory, especially when the length of the string increases. I asked a younger twin brother of the question here: Turn Excel range into VBA string where you will find suggestions how to prepare such a string from Excel range.
Bounty I decided to award Matt. I weighed highly Sean Lange's answer. Thank you Sean. I liked Matt's answer for its simplicity and shortness. Different approaches apart from Matt's and Sean's could be in parallel use so for the time being I am not accepting any answer (update: Finally, after a few months, I have accepted Matt's answer). I wish to thank Ahmed Saeed for his idea with VALUES, for it is a nice evolution of the answer I began with. Of course, it is no match for the Matt's or Sean's. I upvoted every answer. I will appreciate any feedback from you on using these methods. Thank you for the quest.