要分隔值,您可以使用 dbo.SplitStrings_CTE 函数
CREATE FUNCTION dbo.SplitStrings_CTE(@List nvarchar(max), @Delimiter nvarchar(1))
RETURNS @returns TABLE(val nvarchar(max), [level] int, PRIMARY KEY CLUSTERED([level]))
AS
BEGIN
;WITH cte AS
(
SELECT SUBSTRING(@List, 0, CHARINDEX(@Delimiter, @List)) AS val,
CAST(STUFF (@List + @Delimiter, 1, CHARINDEX(@Delimiter, @List), '') AS nvarchar(max)) AS stval,
1 AS [level]
UNION ALL
SELECT SUBSTRING(stval, 0, CHARINDEX(@Delimiter, stval)),
CAST(STUFF (stval, 1, CHARINDEX(@Delimiter, stval), '') AS nvarchar(max)),
[level] + 1
FROM cte
WHERE stval != ''
)
INSERT @returns
SELECT REPLACE(val, ' ', '') AS val, [level]
FROM cte
RETURN
END
创建函数后,使用此 UPDATE 语句
;WITH cte AS
(
SELECT t.OriginalFile, t.EmployeeID, t.EmployeeTitle, t.Location, t.ApplicationID,
NewEmployeeID = MAX(CASE WHEN o.level = 1 THEN o.val END) OVER(),
NewEmployeeTitle = MAX(CASE WHEN o.level = 2 THEN o.val END) OVER(),
NewLocation = MAX(CASE WHEN o.level = 3 THEN o.val END) OVER(),
NewApplicationID = MAX(CASE WHEN o.level = 4 THEN o.val END) OVER()
FROM dbo.UploadAppTable t CROSS APPLY dbo.SplitStrings_CTE(t.OriginalFile, '-') o
)
UPDATE cte
SET EmployeeID = NewEmployeeID,
EmployeeTitle = NewEmployeeTitle,
Location = NewLocation,
ApplicationID = NewApplicationID
SQLFiddle上的演示
用于多次更新的 OR UPDATE 语句
;WITH cte AS
(
SELECT t.OriginalFile, t.EmployeeID, t.EmployeeTitle, t.Location, t.ApplicationID,
NewEmployeeID = MAX(CASE WHEN o.level = 1 THEN o.val END) OVER(PARTITION BY t.OriginalFile),
NewEmployeeTitle = MAX(CASE WHEN o.level = 2 THEN o.val END) OVER(PARTITION BY t.OriginalFile),
NewLocation = MAX(CASE WHEN o.level = 3 THEN o.val END) OVER(PARTITION BY t.OriginalFile),
NewApplicationID = MAX(CASE WHEN o.level = 4 THEN o.val END) OVER(PARTITION BY t.OriginalFile)
FROM dbo.UploadAppTable t CROSS APPLY dbo.SplitStrings_CTE(t.OriginalFile, '-') o
)
UPDATE cte
SET EmployeeID = NewEmployeeID,
EmployeeTitle = NewEmployeeTitle,
Location = NewLocation,
ApplicationID = NewApplicationID
SQLFiddle上的演示