需要SQL触发器来根据破折号分隔符拆分字符串

时间:2013-05-01 15:10:22

标签: sql-server-2005 delimiter insert-update

我正在寻找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

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

你想做OriginalFile.Split('-')之类的事,对吧?遗憾的是,SQL Server中没有可用的内部字符串拆分,您必须自己滚动。事实上,Erland Sommarskog通过一些你可以找到的优秀文章here为每个人节省了太多担心的麻烦。

答案 1 :(得分: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上的演示