T-Sql修改插入SProc如果存在则更新

时间:2010-02-08 10:16:12

标签: tsql stored-procedures

方案

我有一个用T-Sql编写的存储过程,用于将数据作为XML插入表中。 由于数据定期更新,我希望更新行(如果它们已经存在)(除了首次运行应用程序时,它们将始终存在)。

问题

下面是我的Insert Sproc的代码,但是我似乎无法在存储过程的更新方面进行锻炼。我会感激一些帮助。

CODE

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[INS_Curve] 
(
 @Curve varchar(MAX)
)
AS
DECLARE @handle int
 exec sp_xml_preparedocument @handle OUTPUT, @Curve

 INSERT INTO CurveDB..tblCurve(LoadID,BusinessDate, Factor)
  SELECT LoadID,BusinessDate, Factor
  FROM OPENXML(@handle, 'NewDataSet/Table1',2)
  WITH(
  LoadID int,
  BusinessDate DateTime,
  Factor float
  ) 

   exec sp_xml_removedocument @handle

1 个答案:

答案 0 :(得分:1)

不是直接插入目标表,而是将XML Document中的数据放入临时表中,然后从那里INSERT / UPDATE目标......

DECLARE @tabTemporary TABLE
(
  LoadID INT,
  BusinessDate DATETIME,
  Factor FLOAT
)

exec sp_xml_preparedocument @handle OUTPUT, @Curve

 INSERT INTO @tabTemporary (LoadID,BusinessDate, Factor)
  SELECT LoadID,BusinessDate, Factor
  FROM OPENXML(@handle, 'NewDataSet/Table1',2)
  WITH(
  LoadID int,
  BusinessDate DateTime,
  Factor float
  )

exec sp_xml_removedocument @handle

 INSERT INTO CurveDB..tblCurve
 ( LoadID, BusinessDate, Factor )
 SELECT LoadID, BusinessDate, Factor
 FROM @tabTemporary T1
 WHERE NOT EXISTS
 (
 SELECT 1 FROM CurveDB..tblCurve T2 WHERE T1.LoadID = T2.LoadID
 )

 UPDATE T1
 SET T1.BusinessDate = T2.BusinessDate, T1.Factor = T2.Factor
 FROM CurveDB..tblCurve T1
 INNER
 JOIN @tabTemporary T2
 ON T1.LoadID = T2.LoadID

注意:我假设“LoadID”是唯一/主键

<强>更新

在Sql Server 2008中引入的"UPSERT" functionality可能也很有用。