2017-06-22 46 views
-1
declare @set varchar(50) 
set @set = '1,4,2' 

輸出: -產生一系列

1,1,1 
    1,2,1 
    1,3,1 
    1,4,1 
    1,1,2 
    1,2,2  
    1,3,2 
    1,4,2 
+0

你在問什麼?確切的問題是什麼?你有什麼嘗試? – Unknown6656

回答

2

下面是如果需要,通過增加堆疊CTE使用Number表和Parsename功能

DECLARE @set varchar(50) 
SET @set = replace(reverse('1,4,2'),',','.') 

;WITH lv0 AS (SELECT 0 g UNION ALL SELECT 0) 
    ,lv1 AS (SELECT 0 g FROM lv0 a CROSS JOIN lv0 b) -- 4 
    ,lv2 AS (SELECT 0 g FROM lv1 a CROSS JOIN lv1 b) -- 16 
    ,lv3 AS (SELECT 0 g FROM lv2 a CROSS JOIN lv2 b) -- 256 
    ,Tally (n) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM lv3), 
    fst as (SELECT col1 = n FROM Tally where n <= parsename(@set,1)), 
    scd as (SELECT col2 = n FROM Tally where n <= parsename(@set,2)), 
    thd as (SELECT col3 = n FROM Tally where n <= parsename(@set,3)) 
SELECT * 
FROM fst 
     LEFT JOIN scd ON 1 = 1 
     LEFT JOIN thd ON 1 = 1 
ORDER BY col1,col3,col2 

你可以增加數一招一些更多CROSS JOIN's

結果:

╔══════╦══════╦══════╗ 
║ col1 ║ col2 ║ col3 ║ 
╠══════╬══════╬══════╣ 
║ 1 ║ 1 ║ 1 ║ 
║ 1 ║ 2 ║ 1 ║ 
║ 1 ║ 3 ║ 1 ║ 
║ 1 ║ 4 ║ 1 ║ 
║ 1 ║ 1 ║ 2 ║ 
║ 1 ║ 2 ║ 2 ║ 
║ 1 ║ 3 ║ 2 ║ 
║ 1 ║ 4 ║ 2 ║ 
╚══════╩══════╩══════╝ 

欲瞭解更多信息的Numbers表格

Tally Tables in T-SQL

What is the best way to create and populate a numbers table?

+0

thansk爲您的答案。但它不會像預期的那樣在輸出中生成該系列 –

+0

@PratikSharma - 添加了'order by'您是否檢查了最新的代碼?更新與輸出 –

+0

感謝哥們,它如預期般運作良好。可以請你幫助我,因爲在另一種情況下,預期的輸入字符串可能只有'1,4'。在這種情況下,它不返回任何結果集。如果代碼可以在兩種類型的輸入上工作,這將非常有幫助。 –

1

這是一個使用遞歸CTE與數字建立帳簿桌的解決方案。
因此,最大數量不是一個固定的事情。

然後它將集合中的數字連接到它們。

並且concat用於生成集合。

DECLARE @set varchar(10); 
SET @set = '1,4,2'; 

;WITH S AS 
( 
    select 
    cast(parsename(revset,1)as int) as n1, 
    cast(parsename(revset,2)as int) as n2, 
    cast(parsename(revset,3)as int) as n3 
    from (
    select replace(reverse(@set),',','.') revset 
    ) q 
), 
N AS 
(
    select 1 as n 
    union all 
    select n+1 
    from N, S 
    where (N.n < S.n1 or N.n < S.n2 or N.n < S.n3) 
) 
select 
concat(nr1.n,',',nr2.n,','+cast(nr3.n as varchar(2))) as [Sets] 
from S 
join N nr1 on (nr1.n <= S.n1) 
join N nr2 on (nr2.n <= S.n2) 
left join N nr3 on (nr3.n <= S.n3) 
order by nr3.n, nr2.n, nr1.n; 

返回:

Sets 
----- 
1,1,1 
1,2,1 
1,3,1 
1,4,1 
1,1,2 
1,2,2 
1,3,2 
1,4,2 

它仍然會如果你確信工作,如果@set只有2號(注意左連接上N3)

而且這些數字不會超過9,那麼可以通過用遞歸值列表替換遞歸CTE來簡化查詢。
例如:

N AS (select n from (values (1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n)) 
+0

@LukStroms尼斯解決方案。謝謝哥們!! –