Change T-Sql Paste SProc to Update if Exists

Scenario

I have a stored procedure written in T-Sql that I use to insert data into a table as XML. Since the data is updated regularly, I want the rows to be updated if they already exist (in addition, when the application starts, they will always exist).

Question

The following is the code for my Insert Sproc, however I cannot process the update part of the stored procedure and would be happy to help.

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
+3
source share
1 answer

Instead of pasting directly into the target table, put the data in an XML document into a temporary table, and then INSERT / UPDATE the target from there ...

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" - /

UPDATE

"UPSERT" , Sql Server 2008, .

+1

Source: https://habr.com/ru/post/1731847/


All Articles