How to Generate 2 Levels Loop - sql

If I have 2 variables
A = 2
B = 3
I want to generate result like this
A | B | Text
1 | 1 | Text1
1 | 2 | Text2
1 | 3 | Text3
2 | 1 | Text4
2 | 2 | Text5
2 | 3 | Text6
I try to Google and can achieved 1 level with this query
declare #start int = 1
declare #end int = 3
;with numcte
AS
(
SELECT #start as [SEQUENCE]
UNION all
SELECT [SEQUENCE] + 1
FROM numcte WHERE [SEQUENCE] < #end
)
SELECT [SEQUENCE], 'text' + CAST([SEQUENCE] as varchar) as [text] FROM numcte
How can I achieve 2 levels loop?

One rather simple method is:
select a.a, b.b, concat('text', row_number() over (order by a, b))
from (values (1), (2)) a(a) cross join
(values (1), (2), (3)) b(b);
Or if you really want to declare variables:
declare #a int = 2;
declare #b int = 3;
with n as (
select 1 as n union all
select n + 1
from n
where n < #a or n < #b
)
select na.n as a, nb.n as b, concat('text', row_number() over (order by na.n, nb.n))
from n na join
n nb
on na.n <= #a and nb.n <= #b;
Here is a db<>fiddle.

Use a numbers table (many examples you can use by searching). One way to produce what is likely a vastly simplified example is:
with cte as (
select 1 as num
union all select num + 1 from cte where num < 3 )
select cte.num, cte2.num from cte
cross join cte as cte2
where cte.num in (1, 2)
order by cte.num, cte2.num
;
Work through that - it may look daunting. Start thinking in terms of sets! Fiddle

Related

How to arrange continuous serial number in to two or multiple column sequentially in sql server?

I want to print or display 1 to 10 or any max number in two column format using MS Sql-Server query.
Just like below attached screen shot image.
So please give any suggestion.
Using a couple of inline tallies would be way faster than a WHILE. This version will go up to 1000 integers (500 rows):
DECLARE #Start int = 1,
#End int = 99;
SELECT TOP(CONVERT(int,CEILING(((#End*1.) - #Start + 1)/2)))
(ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1)*2 + #Start AS Number1,
CASE WHEN (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1)*2 + #Start +1 <= #End THEN (ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1)*2 + #Start +1 END AS Number2
FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N1(N)
CROSS APPLY (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N2(N)
CROSS APPLY (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N3(N);
An alternative way that looks less messy with the CASE and TOP would be to use a couple of CTEs:
WITH Tally AS(
SELECT TOP(#End - #Start + 1)
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 + #Start AS I
FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N1(N)
CROSS APPLY (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N2(N)
CROSS APPLY (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N3(N)),
Numbers AS(
SELECT I AS Number1,
LEAD(I) OVER (ORDER BY I) AS Number2
FROM Tally)
SELECT Number1,
Number2
FROM Numbers
WHERE Number1 % 2 = #Start % 2;
I like to use recursive queries for this:
with cte (num1, num2) as (
select 1, 2
union all
select num1 + 2, num2 + 2 from cte where num2 < 10
)
select * from cte order by num1
You control the maximum number with the inequality condition in the recursive member of the cte.
If you need to generate more than 100 rows, you need to add option(maxrecursion 0) at the very end of the query.
Assuming you are starting with a table with one column, you can use:
select min(number), max(number)
from sample_data
group by floor( (number - 1) / 2);
Alternatively, set-based solution using window functions:
use tempdb
;with sample_data as (
select 1 as val union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9 union all
select 10
)
, sample_data_split as
(
select
val
, 2- row_number() over (order by val) % 2 as columnid
, NTILE((select count(*) / 2 from sample_data) ) over (order by val) groupid
from sample_data
)
the intermediate result of sample_data_split is:
val columnid groupid
1 1 1
2 2 1
3 1 2
4 2 2
5 1 3
6 2 3
7 1 4
8 2 4
9 1 5
10 2 5
and then to get the resultset into a desired format:
select
min(case when columnid = 1 then val end) as column1
, min(case when columnid = 2 then val end) as column2
from sample_data_split
group by groupid
column1 column2
1 2
3 4
5 6
7 8
9 10
Those CTEs can be merged into a single SELECT:
select
min(case when columnid = 1 then val end) as column1
, min(case when columnid = 2 then val end) as column2
from
(
select
val
, 2- row_number() over (order by val) % 2 as columnid
, NTILE((select count(*) / 2 from sample_data) ) over (order by val) groupid
from sample_data
) d
group by groupid
The positive side of a such approach, that it scales well and has no upper boundary on how much rows to be processed
So I got this solution on it as below...
declare #t table
(
id int identity(1,1),
Number_1 int,
Number_2 int
)
declare #min int=1
declare #max int=10
declare #a int=0;
declare #id int=0
while(#min<=#max)
begin
if(#a=0)
begin
insert into #t
select #min,null
set #a=1
end
else if(#a=1)
begin
select top 1 #id=id from #t order by id desc
update #t set Number_2=#min where id=#id
set #a=0
end
set #min=#min+1
end
select Number_1,Number_2 from #t

SQL: Repeat patterns between date range

DECLARE
#startDate date = '2020-07-03'
#endDate date = 2020-07-06'
I have a tabe as below
---------------------------------------------------------
|EmployeeID | EmpName |Pattern | Frequency |
---------------------------------------------------------
| 11 | X | 1,2,3 | 1 |
| 12 | Y | 4,5 | 1 |
| 13 | Y | 1,2 | 3 |
| 14 | Z | 1,2 | 2 |
---------------------------------------------------------
AND I want to generate dates between given date range.
WANT result table as bellows:
--------------------------------
| EmpId | Dates | Pattern |
--------------------------------
| 11 |2020-07-03 | 1 |
| 11 |2020-07-04 | 2 |
| 11 |2020-07-05 | 3 |
| 11 |2020-07-06 | 1 |
| 12 |2020-07-03 | 4 |
| 12 |2020-07-04 | 5 |
| 12 |2020-07-05 | 4 |
| 12 |2020-07-06 | 5 |
| 13 |2020-07-03 | 1 |
| 13 |2020-07-04 | 1 |
| 13 |2020-07-05 | 1 |
| 13 |2020-07-06 | 2 |
| 14 |2020-07-03 | 1 |
| 14 |2020-07-04 | 1 |
| 14 |2020-07-05 | 2 |
| 14 |2020-07-06 | 2 |
Generate the dates as per given date range for each employee and repeat the pattern for each employee as per their pattern and frequency(days).
means as per frequency(days) pattern will change.
What I have acheived :
Able to generate the records for each employees between the given date range.
What I am not able to get:
I am not able to repeat the pattern based on the frequency for each employee between the date range.
I am able achieve everything but need little help while repeating the pattern based on frequency.*
Note:
Data are storing in this way only.. now I won't change existing schema...
I've came up with this. It's basically a splitter, a tally table and some logic.
Joining (Frequency)-Amount of Tally-datasets with the splitted pattern for the correct amount of pattern-values. Sorting them by their position in the pattern-string.
Join everything together and repeat the pattern by using modulo.
DECLARE #t TABLE( EmployeeID INT
, EmpName VARCHAR(20)
, Pattern VARCHAR(255)
, Frequency INT )
DECLARE #startDate DATE = '2020-07-03'
DECLARE #endDate DATE = '2020-07-09'
INSERT INTO #t
VALUES (11, 'X', '1,2,3', 1),
(12, 'Y', '4,5', 1),
(13, 'Y', '1,2', 3),
(14, 'Z', '1,2', 2)
DECLARE #delimiter CHAR(1) = ',';
WITH split(Txt
, i
, elem
, EmployeeID)
AS (SELECT STUFF(Pattern, 1, CHARINDEX(#delimiter, Pattern+#delimiter+'~'), '')
, 1
, CAST(LEFT(Pattern, CHARINDEX(#delimiter, Pattern+#delimiter+'~')-1) AS VARCHAR(MAX))
, EmployeeID
FROM #t
UNION ALL
SELECT STUFF(Txt, 1, CHARINDEX(#delimiter, Txt+#delimiter+'~'), '')
, i + 1
, CAST(LEFT(Txt, CHARINDEX(#delimiter, Txt+#delimiter+'~')-1) AS VARCHAR(MAX))
, EmployeeID
FROM split
WHERE Txt > ''),
E1(N) AS (SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1), --10E+1 or 10 rows
E2(N) AS (SELECT 1 FROM E1 AS a, E1 AS b), --10E+2 or 100 rows
E4(N) AS (SELECT 1 FROM E2 AS a, E2 AS b), --10E+4 or 10,000 rows
E8(N) AS (SELECT 1 FROM E4 AS a , E4 AS b), --10E+8 or 100,000,000 rows
PatternXFrequency(EmployeeID
, Sort
, elem)
AS (SELECT split.EmployeeID
, ROW_NUMBER() OVER(PARTITION BY split.EmployeeID ORDER BY i) - 1
, elem
FROM split
INNER JOIN #t AS t ON t.EmployeeID = split.EmployeeID
CROSS APPLY (SELECT TOP (t.Frequency) 1
FROM E8
) AS Freq(Dummy))
SELECT EmployeeID
, DATEADD(DAY, i_count, #startDate) AS Dates
, elem
FROM (SELECT DATEDIFF(DAY, #startDate, #endDate) + 1) AS t_datediff(t_days)
CROSS APPLY (SELECT TOP (t_days) ROW_NUMBER() OVER(ORDER BY (SELECT 0) ) - 1 FROM E8
) AS t_dateadd(i_count)
CROSS APPLY (SELECT PatternXFrequency.*
FROM (SELECT DISTINCT EmployeeID FROM #t) AS t(EmpID)
CROSS APPLY (SELECT COUNT(Sort)
FROM PatternXFrequency
WHERE EmployeeID = EmpID
) AS EmpPattern(sortCount)
CROSS APPLY (SELECT *
FROM PatternXFrequency
WHERE EmployeeID = EmpID
AND Sort = ((i_count % sortCount))
) AS PatternXFrequency
) AS t
ORDER BY t.EmployeeID
, Dates
This isn't particularly pretty, but it avoids the recursion of a rCTE, so should provide a faster experience. As STRING_SPLIT still doesn't know what ordinal position means, we have to use something else here; I use DelimitedSplit8k_LEAD.
I also assume your expected results are wrong, as they stop short of your end date (20200709). This results in the below:
CREATE TABLE dbo.YourTable (EmployeeID int,
EmpName char(1),
Pattern varchar(8000), --This NEEDS fixing
Frequency tinyint);
INSERT INTO dbo.YourTable
VALUES(11,'X','1,2,3',1),
(12,'Y','4,5',1),
(13,'Y','1,2',3),
(14,'Z','1,2',2);
GO
DECLARE #StartDate date = '20200703',
#EndDate date = '20200709';
WITH CTE AS(
SELECT *,
MAX(ItemNumber) OVER (PARTITION BY EmployeeID) AS MaxItemNumber
FROM dbo.YourTable YT
CROSS APPLY dbo.DelimitedSplit8K_LEAD(YT.Pattern,',') DS),
N AS(
SELECT N
FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
SELECT TOP (SELECT DATEDIFF(DAY,#startDate, #EndDate)+1)
ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 AS I
FROM N N1, N N2, N N3) --1000 Rows
SELECT C.EmployeeID,
DATEADD(DAY,T.I, #StartDate),
C.Item
FROM CTE C
JOIN Tally T ON ISNULL(NULLIF((T.I +1) % C.MaxItemNumber,0),C.MaxItemNumber) = C.ItemNumber
ORDER BY EmployeeID,
T.I;
GO
DROP TABLE dbo.YourTable;
Like mentioned in the comments fix your data model.
Your output pattern is a little bit strange.
But is it something like this you are looking for?
DECLARE #startDate date = '2020-07-03'
DECLARE #endDate date = '2020-07-09'
DECLARE #Dates TABLE([Date] Date)
;WITH seq(n) AS
(
SELECT 0 UNION ALL SELECT n + 1 FROM seq
WHERE n < DATEDIFF(DAY, #StartDate, #endDate)
)
INSERT INTO #Dates ([Date])
SELECT DATEADD(Day,n, cast(GetDate() as date)) Date
FROM seq
ORDER BY n
OPTION (MAXRECURSION 0);
SELECT e.EmployeeId, d.Date, x.Value Pattern
FROM Employee e
CROSS APPLY STRING_SPLIT(e.Pattern, ',') x
INNER JOIN #Dates d on 1=1
-- Correct for the first iteration of the pattern
AND DATEDIFF(DAY, DATEADD(DAY, -1, #StartDate), d.Date) = x.Value

Select non existing Numbers from Table each ID

I‘m new in learning TSQL and I‘m struggling getting the numbers that doesn‘t exist in my table each ID.
Example:
CustomerID Group
1 1
3 1
6 1
4 2
7 2
I wanna get the ID which does not exist and select them like this
CustomerID Group
2 1
4 1
5 1
5 2
6 2
....
..
The solution by usin a cte doesn‘t work well or inserting first the data and do a not exist where clause.
Any Ideas?
If you can live with ranges rather than a list with each one, then an efficient method uses lead():
select group_id, (customer_id + 1) as first_missing_customer_id,
(next_ci - 1) as last_missing_customer_id
from (select t.*,
lead(customer_id) over (partition by group_id order by customer_id) as next_ci
from t
) t
where next_ci <> customer_id + 1
Cross join 2 recursive CTEs to get all the possible combinations of [CustomerID] and [Group] and then LEFT join to the table:
declare #c int = (select max([CustomerID]) from tablename);
declare #g int = (select max([Group]) from tablename);
with
customers as (
select 1 as cust
union all
select cust + 1
from customers where cust < #c
),
groups as (
select 1 as gr
union all
select gr + 1
from groups where gr < #g
),
cte as (
select *
from customers cross join groups
)
select c.cust as [CustomerID], c.gr as [Group]
from cte c left join tablename t
on t.[CustomerID] = c.cust and t.[Group] = c.gr
where t.[CustomerID] is null
and c.cust > (select min([CustomerID]) from tablename where [Group] = c.gr)
and c.cust < (select max([CustomerID]) from tablename where [Group] = c.gr)
See the demo.
Results:
> CustomerID | Group
> ---------: | ----:
> 2 | 1
> 4 | 1
> 5 | 1
> 5 | 2
> 6 | 2

Divide the coordinates into X and Y coordinates from a table having geometry data in SQL Server 2012

I have a table with a column Shape of geometry datatype.
This is the data in Shape :
POLYGON ((565542.98375 2127263.4997410, 565538.48450 2127261.3187302, 565541.96658 2127254.1162, 565546.465835 2127256.297297, 565542.9837 2127263.49974102))
POLYGON ((565547.281621307 2127097.9410014, 565549.457915 2127093.43948425, 565553.577449391 2127084.9189882, 565568.882475 2127092.31709055, 565562.586805441 2127105.3404182, 565547.2816807 2127097.94105044))
and so on....
I need output as
ID | X | Y
---+-----------------+-----------------
1 | 565542.98375 | 2127263.4997410
1 | 565538.48450 | 2127261.3187302
1 | 565541.96658 | 2127254.1162
1 | 565546.465835 | 2127256.297297
1 | 565542.9837 | 2127263.49974102
2 | 565547.281627 | 2127097.9410014
2 | 565549.457915 | 2127093.43948425
2 | 565553.5774391 | 2127084.9189882
and so on in table format
If you first create a Numbers table with sequential integers from 1 upwards and at least as many rows as the maximum number of points you will ever be dealing with then this is straightforward.
SELECT S.id,
X = S.GeomCol1.STPointN(N.number).STX,
Y = S.GeomCol1.STPointN(N.number).STY
FROM SpatialTable S
JOIN Numbers N
ON N.number <= S.GeomCol1.STNumPoints()
Code to create and populate a Numbers table is below.
CREATE TABLE dbo.Numbers(Number INT PRIMARY KEY);
WITH E1(N) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
) -- 1*10^1 or 10 rows
, E2(N) AS (SELECT 1 FROM E1 a, E1 b) -- 1*10^2 or 100 rows
, E4(N) AS (SELECT 1 FROM E2 a, E2 b) -- 1*10^4 or 10,000 rows
, E8(N) AS (SELECT 1 FROM E4 a, E4 b) -- 1*10^8 or 100,000,000 rows
, Nums AS (SELECT TOP (10000000) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS N FROM E8)
INSERT INTO dbo.Numbers
SELECT N
FROM Nums
Here is an option which will work with 2012. Note that we maintain the sequence (RetSeq)
Example
SELECT A.ID
,B.RetSeq
,X = left(C.RetVal,charindex(' ',C.RetVal)-1)
,Y = substring(C.RetVal,charindex(' ',C.RetVal)+1,50)
FROM YourTable A
Cross Apply (
Select RetSeq = row_number() over (Order By 1/0)
,RetVal = B2.i.value('(./text())[1]', 'varchar(100)')
From (Select x = Cast('<x>' + replace(A.Shape.STAsText(),',','</x><x>')+'</x>' as xml)) as B1
Cross Apply x.nodes('x') AS B2(i)
) B
Cross Apply ( values (ltrim(rtrim(replace(replace(replace(B.RetVal,'POLYGON',''),'(',''),')','')))) ) C(RetVal)
Returns
ID RetSeq X Y
1 1 565542.98375 2127263.499741
1 2 565538.4845 2127261.3187302
1 3 565541.96658 2127254.1162
1 4 565546.465835 2127256.297297
1 5 565542.98375 2127263.499741
2 1 565547.281621307 2127097.9410014
2 2 565549.457915 2127093.43948425
2 3 565553.577449391 2127084.9189882
2 4 565568.882475 2127092.31709055
2 5 565562.586805441 2127105.3404182
2 6 565547.281621307 2127097.9410014
EDIT
Martin Smith's solution should really be the ACCEPTED answer. If you can't create a numbers table, you can use an ad-hoc tally table.
Example
Select A.ID
,Seq = B.N
,X = Shape.STPointN(N).STX
,Y = Shape.STPointN(N).STY
From YourTable A
Cross Apply (Select Top (Shape.STNumPoints()) N=Row_Number() Over (Order By 1/0) From master..spt_values n1, master..spt_values n2 ) B
Requested EDIT
;with cte as (
SELECT A.ID
,B.RetSeq
,X = left(C.RetVal,charindex(' ',C.RetVal)-1)
,Y = substring(C.RetVal,charindex(' ',C.RetVal)+1,50)
,Cnt = max(B.RetSeq) over (Partition by A.ID)
FROM YourTable A
Cross Apply (
Select RetSeq = row_number() over (Order By 1/0)
,RetVal = B2.i.value('(./text())[1]', 'varchar(100)')
From (Select x = Cast('<x>' + replace(A.Shape.STAsText(),',','</x><x>')+'</x>' as xml)) as B1
Cross Apply x.nodes('x') AS B2(i)
) B
Cross Apply ( values (ltrim(rtrim(replace(replace(replace(B.RetVal,'POLYGON',''),'(',''),')','')))) ) C(RetVal)
)
Select *
From cte
Where RetSeq<Cnt
Order By ID,RetSeq
OR ... Notice the minus 1 in the TOP
Select A.ID
,Seq = B.N
,X = Shape.STPointN(N).STX
,Y = Shape.STPointN(N).STY
From YourTable A
Cross Apply (Select Top (Shape.STNumPoints() - 1) N=Row_Number() Over (Order By 1/0) From master..spt_values n1, master..spt_values n2 ) B
Naive approach with parsing string(SQL Server 2017):
CREATE TABLE SpatialTable
( id int IDENTITY (1,1),
GeomCol1 geometry );
INSERT INTO SpatialTable
SELECT geometry::STGeomFromText(
'POLYGON ((565542.98375 2127263.4997410, 565538.48450 2127261.3187302, 565541.96658 2127254.1162, 565546.465835 2127256.297297, 565542.98375 2127263.4997410))',0)
UNION ALL
SELECT geometry::STGeomFromText('POLYGON ((565547.281621307 2127097.9410014, 565549.457915 2127093.43948425, 565553.577449391 2127084.9189882, 565568.882475 2127092.31709055, 565562.586805441 2127105.3404182, 565547.281621307 2127097.9410014))',0);
Query:
SELECT ID, s1.rn, s3.x, s3.y, GeomCol1
FROM SpatialTable s
CROSS APPLY (SELECT value, ROW_NUMBER() OVER(ORDER BY 1/0) AS rn
FROM STRING_SPLIT(s.GeomCol1.STAsText() ,',')) s1
CROSS APPLY (SELECT TRIM(TRANSLATE(value, 'POLYGON()', ' '))) s2(r)
CROSS APPLY (SELECT TRY_CAST(LEFT(s2.r, CHARINDEX(' ',s2.r)) AS DECIMAL(18,6)),
TRY_CAST(RIGHT(s2.r,LEN(s2.r)-CHARINDEX(' ',s2.r)) AS DECIMAL(18,6))
) s3(x,y);
db<>fiddle demo
You can use the geometry methods in a CROSS APPLY to get those values.
Then get the X and Y from the points.
In the example below the numbers come from spt_values, but that's just 1 one of the methods to obtain a Tally table with numbers in a range.
WITH NUMS AS
(
SELECT DISTINCT number as n
FROM master..[spt_values]
WHERE number between 1 and 128
)
SELECT ID, GeoPoint.STX AS X, GeoPoint.STY AS Y
FROM Shapes s
CROSS APPLY
(
SELECT n as PointN, Shape.STPointN(n) AS GeoPoint
FROM NUMS
WHERE n BETWEEN 1 AND Shape.STNumPoints()
) ca;
Test on db<>fiddle here

Remove 'cross' duplicate result for double cross apply

I have the following data in a column:
5;ABC|1;XYZ
I would like to split the value on the '|' delimiter and then split every result on the ';' delimiter.
I have the following query, but unfortenately it gives me (sort of) duplicate results.
DECLARE #MyTable TABLE ( Code VARCHAR(100) )
INSERT INTO #MyTable
VALUES ( '5;ABC|1;XYZ' );
WITH Query AS
(
SELECT T1.RowNum, SubSplit.Value FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY Code) as RowNum, Split.Value FROM #MyTable
CROSS APPLY SplitString(Code, '|') AS Split
) T1
CROSS APPLY SplitString(Value, ';') AS SubSplit
)
SELECT q1.Value AS [Left], q2.Value AS [Right] FROM Query q1
INNER JOIN Query q2 ON q1.RowNum = q2.RowNum AND q1.Value <> q2.Value
The result is:
But what I would like is:
How can I achieve this?
Edit
For completeness, this is the SplitString function I use:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION SplitString
(
-- Add the parameters for the function here
#input varchar(8000),
#delimiter varchar(1)
)
RETURNS TABLE
AS
RETURN
(
WITH cte AS
(
SELECT 0 a, 1 b
UNION ALL
SELECT b, CHARINDEX(#delimiter, #input, b) + LEN(#delimiter)
FROM CTE
WHERE b > a
)
SELECT SUBSTRING(#input, a,
CASE WHEN b > LEN(#delimiter)
THEN b - a - LEN(#delimiter)
ELSE LEN(#input) - a + 1 END) Value
FROM cte WHERE a > 0
)
GO
Add another ROW_NUMBER in the outer query:
SQL Fiddle
Query 1:
DECLARE #MyTable TABLE ( Code VARCHAR(100) )
INSERT INTO #MyTable
VALUES ( '5;ABC|1;XYZ|6;HXS|7;GGH' )
;WITH Query AS
(
SELECT T1.RowNum, SubSplit.Value,
ROW_NUMBER() OVER (PARTITION BY T1.RowNum ORDER BY SubSplit.Value) as RowNum1
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY Code) as RowNum, Split.Value FROM #MyTable
CROSS APPLY SplitString(Code, '|') AS Split
) T1
CROSS APPLY SplitString(Value, ';') AS SubSplit
)
SELECT q1.Value AS [Left], q2.Value AS [Right] FROM Query q1
INNER JOIN Query q2 ON q1.RowNum = q2.RowNum AND q1.RowNum1 = 1 AND q2.RowNum1 = 2
Results:
| Left | Right |
|------|-------|
| 5 | ABC |
| 1 | XYZ |
| 6 | HXS |
| 7 | GGH |
Update:
The use of the ROW_NUMBER() in the outer query will only work if the Left is less then Right when diong the string comparison. It will not work correctly for the '6;123' value. Therefore, there is a better approach by using an enhanced SplitString function as per below:
SQL Fiddle
MS SQL Server 2014 Schema Setup:
CREATE FUNCTION SplitString
(
-- Add the parameters for the function here
#input varchar(8000),
#delimiter varchar(1)
)
RETURNS TABLE
AS
RETURN
(
WITH cte AS
(
SELECT 0 a, 1 b, 0 rn
UNION ALL
SELECT b, CHARINDEX(#delimiter, #input, b) + LEN(#delimiter), rn + 1
FROM CTE
WHERE b > a
)
SELECT SUBSTRING(#input, a,
CASE WHEN b > LEN(#delimiter)
THEN b - a - LEN(#delimiter)
ELSE LEN(#input) - a + 1 END) Value,
rn
FROM cte WHERE a > 0
)
Query 1:
DECLARE #MyTable TABLE ( Code VARCHAR(100) )
INSERT INTO #MyTable
VALUES ( '5;ABC|1;XYZ|6;123|7;GGH' )
;WITH Query AS
(
SELECT T1.RowNum, SubSplit.Value,
SubSplit.rn as RowNum1
FROM
(
SELECT Split.rn as RowNum, Split.Value FROM #MyTable
CROSS APPLY SplitString(Code, '|') AS Split
) T1
CROSS APPLY SplitString(Value, ';') AS SubSplit
)
SELECT q1.Value AS [Left], q2.Value AS [Right] FROM Query q1
INNER JOIN Query q2 ON q1.RowNum = q2.RowNum AND q1.RowNum1 = 1 AND q2.RowNum1 = 2
Results:
| Left | Right |
|------|-------|
| 5 | ABC |
| 1 | XYZ |
| 6 | 123 |
| 7 | GGH |