First you can create a function converting a string to table. For instance you can use this one:
CREATE FUNCTION dbo.StringToTable
@Input NVARCHAR (4000),
RETURNS @OutputTable TABLE (val NVARCHAR(50))
DECLARE @val NVARCHAR(50);
WHILE LEN(@Input) > 0
SET @val = LEFT(@Input, ISNULL(NULLIF(CHARINDEX(@Delimiter, @Input) - 1, -1), LEN(@Input)));
SET @Input = SUBSTRING(@Input, ISNULL(NULLIF(CHARINDEX(@Delimiter, @Input), 0), LEN(@Input)) + 1, LEN(@Input));
INSERT INTO @OutputTable (val) VALUES (@val);
Let's write a query which uses this function and generate the result you want to see:
DECLARE @P1 AS NVARCHAR(100) = N'xxx~yyy',
@P2 AS NVARCHAR(100) = N'10~12~15',
@P3 AS NVARCHAR(100) = N'1~2~7';
ROW_NUMBER() OVER( ORDER BY t1.val, t2.val, t3.val) AS rn, *
FROM dbo.StringToTable(@P1, N'~') AS t1
CROSS JOIN dbo.StringToTable(@P2, N'~') AS t2
CROSS JOIN dbo.StringToTable(@P3, N'~') AS t3
Good solution and great use of CROSS JOIN.
Just a comment on the splitter function. I strongly recommend against using a WHILE loop for splitting especially if it's going to be something common place. Please see the following article for some performance tests among splitting methods. The method you have above is known as a "Nibbler".http://www.sqlservercentral.com/articles/Tally+Table/72993/
If you can't use the SQLCLR method for something like this, then the UDF in the article will provide a close second for performance for anything 8K or less. Here's one of performance charts from the article. The skinny black line is the performance before the function was increased in performance by another 10-15% by a suggestion in the discussions that followed the article. As it was, the new function is about 3 times faster than either type of WHILE loop solution. Of course, the SQLCLR is more than twice as fast as even the new solution (again, the skinny black line).
is pronounced ree-bar and is a Modenism for R
First step towards the paradigm shift of writing Set Based code: Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.
Although they tell us that they want it real bad, our primary goal is to ensure that we dont actually give it to them that way.
Although change is inevitable, change for the better is not.
Just because you can do something in PowerShell, doesnt mean you should. Helpful Links:
How to post code problemsHow to post performance problemsForum FAQs