SQL Server 內建並無字串分割函數,常見需求可透過自訂表值函數實現。以下提供一個接受原始字串與分隔符號、回傳分割後各片段及序號的函數 uf_StrSplit。
CREATE FUNCTION uf_StrSplit
(
@origStr VARCHAR(7000), -- 待分割字串
@markStr VARCHAR(100) -- 分隔符號,如 ','
)
RETURNS @splittable TABLE
(
str_id VARCHAR(4000) NOT NULL, -- 序號
string VARCHAR(2000) NOT NULL -- 分割後片段
)
AS
BEGIN
DECLARE @strlen INT, @position INT, @start INT, @sublen INT,
@TEMPstr VARCHAR(200), @TEMPid INT
SELECT @strlen = LEN(@origStr), @start = 1, @sublen = 0,
@position = 1, @TEMPstr = '', @TEMPid = 0
-- 確保字串以分隔符結尾,簡化邏輯
IF (RIGHT(@origStr, 1) <> @markStr)
SET @origStr = @origStr + @markStr
WHILE ((@position <= @strlen) AND (@position != 0))
BEGIN
IF (CHARINDEX(@markStr, @origStr, @position) != 0)
SET @sublen = CHARINDEX(@markStr, @origStr, @position) - @position
ELSE
SET @sublen = @strlen - @position + 1
IF (@position <= @strlen)
BEGIN
SET @TEMPid = @TEMPid + 1
SET @TEMPstr = SUBSTRING(@origStr, @position, @sublen)
INSERT INTO @splittable (str_id, string) VALUES (@TEMPid, @TEMPstr)
IF (CHARINDEX(@markStr, @origStr, @position) != 0)
SET @position = CHARINDEX(@markStr, @origStr, @position) + 1
ELSE
SET @position = @position + 1
END
END
RETURN
END
SELECT * FROM uf_StrSplit('1,1,2,50', ',')
輸出結果:
| str_id | string |
|---|---|
| 1 | 1 |
| 2 | 1 |
| 3 | 2 |
| 4 | 50 |
此函數可直接在查詢中套用,配合 CROSS APPLY 處理資料表欄位分割需求。