[英]sql for how to check if a record exists when inserting from xml
I am inserting records from some XML. 我正在从一些XML插入记录。 I need to check if the record already exists and insert if it doesn't and update if it does.
我需要检查记录是否已经存在,如果不存在则插入,如果存在则进行更新。
This is what i have but there are multiple records returned from the subquery. 这就是我所拥有的,但是从子查询返回了多个记录。
ALTER PROCEDURE [dbo].[InsertOrdersFromXML] (
@xmlData XML
)
AS
begin tran /* default read committed isolation level is fine */
declare @orderId int
set @orderId = (SELECT x.XmlCol.value('OrderNumber[1]', 'int') FROM @xmlData.nodes('//Order') AS x(XmlCol))
if not exists (SELECT StoreorderId FROM Orders with (updlock, rowlock, holdlock) where StoreOrderId = @orderId)
/* insert */
INSERT INTO [dbo].[Orders]
([StoreOrderId]
,[CustomerId]
,[OrderDate]
SELECT
x.XmlCol.value('OrderNumber[1]', 'int') as 'StoreOrderId',
x.XmlCol.value('CustomerID[1]', 'int') as 'CustomerId',
x.XmlCol.value('OrderDate[1]', 'datetime') as ' OrderDate',
FROM @xmlData.nodes('//Order') AS x(XmlCol)
INSERT INTO [dbo].[OrderLines]
([OrderId]
,[StoreOrderId]
,[ProductId]
,[Quantity]
,[ChosenColour]
,[ChosenSize]
,[ShoppingCartRecID])
select (select OrderId from Orders with (updlock, rowlock, holdlock) where storeorderid = x.XmlCol2.value('OrderNumber[1]', 'varchar(25)')),
x.XmlCol2.value('OrderNumber[1]', 'varchar(25)') as ' OrderNumber',
x.XmlCol2.value('ProductID[1]', 'varchar(25)') as ' ProductID',
x.XmlCol2.value('Quantity[1]', 'varchar(25)') as ' Quantity',
x.XmlCol2.value('ChosenColor[1]', 'varchar(25)') as ' ChosenColor',
x.XmlCol2.value('ChosenSize[1]', 'varchar(25)') as ' ChosenSize',
x.XmlCol2.value('ShoppingCartRecID[1]', 'varchar(25)') as ' ShoppingCartRecID'
FROM @xmlData.nodes('//Order/OrderItems/Item') AS x(XmlCol2)
commit
also, how can I add the update part? 另外,如何添加更新部分?
You can simply do this to insert
or update
: 您只需执行以下操作即可
insert
或update
:
if not exists (SELECT StoreorderId FROM Orders with (updlock, rowlock, holdlock)
where StoreOrderId = @orderId)
begin
/* insert */
end
else
begin
/* update */
end
With the multiple records you can use a cursor
around your insert
/ update
statements, like so: 使用多个记录,您可以在
insert
/ update
语句周围使用cursor
,如下所示:
declare order_cursor cursor for
SELECT x.XmlCol.value('OrderNumber[1]', 'int')
FROM @xmlData.nodes('//Order') AS x(XmlCol)
open order_cursor;
fetch next from order_cursor into @orderId
while @@FETCH_STATUS=0
begin
if not exists (SELECT StoreorderId
FROM Orders with (updlock, rowlock, holdlock)
WHERE StoreOrderId = @orderId)
begin
/* insert */
end
else
begin
/* update */
end
fetch next from order_cursor into @orderId
end
close order_cursor;
deallocate order_cursor;
Obviously this isn't tested, but it should set up a cursor
against your XML
, then allocates the @orderId
one row at a time to process the rest of the code. 显然,这没有经过测试,但是它应该在
XML
设置一个cursor
,然后一次分配@orderId
一行,以处理其余的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.