I have a stored procedure written in T-Sql that I use to insert data into a table as XML. Since the data gets updated regularly, I want the rows to be updated if they already exist (Aside from when the application is first run, they will always exist).
Below is the code of my Insert Sproc, however I cannot seem to workout the Update side of the stored procedure & would appreciate some help.
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
Rather than inserting directly into the target table, put the data in the 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
Note: I've assumed that "LoadID" is a unique/primary key
UPDATE
There's also the "UPSERT" functionality introduced in Sql Server 2008 that may be of interest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With