分隔這些值可以使用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
或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
說實話,我從來沒有寫過更新聲明,將更新多列。所以我需要建議,所以我可以嘗試一些。我還沒有嘗試過任何東西。 – user2066533 2013-05-01 15:25:54
看起來像「CHARINDEX」是要用分隔符分割字符串的方法。我只是不知道正確的語法。我還需要將其添加到SQL觸發器。 – user2066533 2013-05-01 15:36:43
*** SQL ***只是*結構化查詢語言* - 許多數據庫系統使用的語言,但不是數據庫產品...類似於觸發器的事物是高度**特定於供應商的 - 因此我們真的需要了解您正在使用的**數據庫系統**(以及哪個版本)(請相應地更新標籤).... – 2013-05-01 15:50:09