Sql-Server

為逗號分隔字元串中的每個值創建一行

  • January 9, 2018

我目前正在嘗試從執行以下操作的表創建視圖:

Table A
╔═════════════╦═══════════════╗ 
║ PART NUMBER ║   FILE NAME   ║
╠═════════════╬═══════════════╣
║  PN0001-01  ║      FOO      ║
║  PN0002-01  ║      BAR      ║
║  PN0003-01  ║    FOO,BAR    ║
║  PN0004-01  ║  BAR,FOO,FOB  ║
╚═════════════╩═══════════════╝

創造

View B
╔═════════════╦═══════════════╗ 
║ PART NUMBER ║   FILE NAME   ║
╠═════════════╬═══════════════╣
║  PN0001-01  ║      FOO      ║
║  PN0002-01  ║      BAR      ║
║  PN0003-01  ║      FOO      ║
║  PN0003-01  ║      BAR      ║
║  PN0004-01  ║      BAR      ║
║  PN0004-01  ║      FOO      ║
║  PN0004-01  ║      FOB      ║
╚═════════════╩═══════════════╝

所以,本質上,我需要從表 A 中獲取記錄並將它們插入到視圖 B 中,如果來自 A 的記錄具有 LIKE '

$$ , $$’ 屬性,然後該欄位在 B 中被拆分為多個記錄,具體取決於“,”出現的次數,每個“,”之間的文本在視圖 B 中被賦予其自己的記錄。

首先,創建一個字元串拆分函式:

CREATE FUNCTION dbo.SplitString
(
   @List      nvarchar(max),
   @Delimiter nvarchar(10)
)
RETURNS TABLE
WITH SCHEMABINDING
AS
 RETURN 
 (
   WITH x(x) AS 
   (
     SELECT 1 UNION ALL SELECT x+1 FROM x 
     WHERE x < (LEN(@List))
   )
   SELECT Item = SUBSTRING(@List, x, 
     CHARINDEX(@Delimiter, @List + @Delimiter, x) - x)
   FROM x WHERE x <= CONVERT(INT, LEN(@List))
     AND SUBSTRING(@Delimiter + @List, x, 1) = @Delimiter  );
GO

然後,您可以簡單地將原始碼與函式交叉應用:

DECLARE @x TABLE(PartNumber nvarchar(255), FileName nvarchar(max));

INSERT @x(PartNumber, FileName) VALUES
('PN0001-01','FOO'),
('PN0002-01','BAR'),
('PN0003-01','FOO,BAR'),
('PN0004-01','BAR,FOO,FOB');

-- INSERT dbo.ViewName(col1,col2)
SELECT x.PartNumber, f.Item
FROM @x AS x
CROSS APPLY dbo.SplitString(x.FileName, N',') AS f;

在 SQL Server 2016 中,您可以使用本機STRING_SPLIT()函式。

引用自:https://dba.stackexchange.com/questions/163401