2017-03-02 68 views
0

我有兩個colums ID和權利的表。 Rights列將保留250個固定字符,如'010111100000000 .... 250次'。現在,我必須拆分權限列字符串,並將結果存儲在臨時表中,其結構ID,權限(0或1),位置(1到250)。假設我最初有5行,然後在臨時表中,我將得到5 * 250 = 1250行。cte在與臨時表和拆分字符串的sql服務器

我已經拆分了單個字符串並使用了遊標,但現在我想避免遊標。我如何才能做到這一點。

declare @temp table(Chars int not null, RowID int not null) 

    --Split the rights string into 250 char rows with RowID as each position 
    ;with cte as 
    (
     select substring(@rights, 1, 1) as Chars, 
       stuff(@rights, 1, 1, '') as rights, 
       1 as RowID 
     union all 
     select substring(rights, 1, 1) as Chars, 
       stuff(rights, 1, 1, '') as rights, 
       RowID + 1 as RowID 
     from cte 
     where len(rights) > 0 

    ) 

    --Get the values in a temporary table except 0 
    insert into @temp select Chars, RowID from cte option (MAXRECURSION 300); 

回答

1

這是怎麼回事?

的理念是:獲得250運行號的列表,並使用SUBSTRING從每個位置讀取一個字符:

DECLARE @tbl TABLE (ID INT IDENTITY,Rights VARCHAR(250)); 
INSERT INTO @tbl VALUES 
('1011101110000101010111000...'), ('0100010111100010101...'); 

WITH Nr250 AS 
(SELECT TOP 250 ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS Nr FROM master.dbo.spt_values) 

SELECT t.ID 
     ,t.Rights 
     ,Nr AS Position 
     ,SUBSTRING(t.Rights,Nr,1) AS PosDigit 
--INTO #SomeTempTable 
FROM Nr250 
CROSS JOIN @tbl AS t 

如果你想寫到一個臨時表這一點,只是--之前INTO刪除

+0

非常感謝它爲我工作 – Anurag