在写这篇文章时,我想出了一个使用交叉应用和自定义拆分功能的简单方法。因此,我将发布我如何使用这个自包含的 SQL 来解决它的问题,而不是仅仅问这个问题;)
-- set up a split function
GO
CREATE FUNCTION [dbo].[TempSplit] (@sep char(1), @s varchar(512))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces
)
GO
-- set up some test data
DECLARE @personroles TABLE
(
idperson INT,
rawroleoptions NVARCHAR(MAX)
)
INSERT INTO @personroles VALUES (1, ';1;2;3;')
INSERT INTO @personroles VALUES (2, ';4;5;6;')
INSERT INTO @personroles VALUES (3, ';7;')
-- the actual work --
;WITH data AS
(
SELECT
p.idperson,
p.rawroleoptions
FROM @personroles p
)
SELECT * FROM data r
CROSS APPLY
(SELECT s AS [ExtractedValue] FROM dbo.TempSplit(';',r.rawroleoptions) WHERE LEN(s)>0) d
-- clean up --
GO
DROP FUNCTION dbo.TempSplit
GO
运行上述内容后,这就是 SQL 输出的内容。