1

我正在为 MSSQL 2005 触发器寻找正确的语法,该触发器将拆分一列的值并更新其他 4 列。

  • 数据库:TestDB
  • 桌子:UploadAppTable

|OriginalFile                 | EmployeeID | EmployeeTitle | Location | ApplicationID 
|0146291-ITDCCT-02-1367413404 |            |               |          |

如果以下,我需要什么。当插入新记录时,我需要 SQL 触发器来更新表。

输出

|OriginalFile                 | EmployeeID | EmployeeTitle | Location | ApplicationID
|0146291-ITDCCT-02-1367413404 | 0146291    | ITDCCT        | 02       | 1367413404

任何帮助将不胜感激。

4

2 回答 2

0

要分隔值,您可以使用 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上的演示

于 2013-05-01T16:26:24.280 回答
0

你想做类似的事情OriginalFile.Split('-'),对吧?遗憾的是,SQL Server 中没有可用的内在字符串拆分,您将不得不推出自己的 . 方便地,Erland Sommarskog 通过您可以在此处找到的一些优秀文章,为大家省去了太多担心它的麻烦。

于 2013-05-01T15:55:13.460 回答