簡體   English   中英

在SQL Server中使用臨時表和拆分字符串進行CTE

[英]cte in sql server with temp table and split string

我有兩個列ID和權限的表。 權限列將以0,1格式(例如“ 010111100000000 .... 250次”)保留250個固定字符。 現在,我必須拆分權限列字符串,並在臨時表中獲取結果,該表將具有結構ID,權限(0或1),位置(1至250)。 假設我最初有5行,那么在臨時表中我將獲得5 * 250 = 1250行。

我已經分割了單個字符串並使用了光標,但是現在我想避免使用光標。 我如何實現這一目標。

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);

那這個呢?

這個想法是:獲取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之前刪除--

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM