我有两个colums ID和权限的表。权利栏将在0,1形式中保留250个固定字符,如'010111100000000 .... 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);
答案 0 :(得分: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