场景:1.Form具有5个记录的gridview。 (绑定记录FROM数据库)2。选择自动完成然后添加到gridview的更多记录。 3.next从该gridview中删除了一条记录,然后通过XML将值传递给DB。像我这样的xml代码
<?xml version="1.0"?>
<ArrayOfLanuageInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SpokenLanuageInfo>
<LanguageId>154</LanguageId>
</SpokenLanuageInfo>
<SpokenLanuageInfo>
<LanguageId>46</LanguageId>
</SpokenLanuageInfo>
<SpokenLanuageInfo>
<LanguageId>53</LanguageId>
</SpokenLanuageInfo>
</ArrayOfLanuageInfo>
here one recoded am deleted ,one record added so how to do ??
-deleted record should remove from table
-new record insert into table
Stored Procedure like this :
// here am deleting all records based on id every time and then inserting table so i don't want like this //
DELETE FROM [dbo].LANGUAGE WHERE [HOSPITAL_ID]=@HOSPITAL_ID
INSERT INTO [dbo].LANGUAGE
(
HOSPITAL_ID, LANGUAGE_ID
)
SELECT @HOSPITAL_ID,LanguageId
FROM
OPENXML(@XmlHandleSAVELANGUAG,'/ArrayOfLanuageInfo/LanuageInfo',2)
WITH
( LanguageId INT )
END
答案 0 :(得分:0)
这是使用SQL MERGE的理想选择。 它允许您根据单个语句中的匹配条件插入/更新/删除。
查看Microsoft Technet reference以获取更多信息。
编辑:这里是使用SQL MERGE和OPENXML
的一些示例代码declare @idoc int;
declare @inputXml xml = N'
<data>
<item>
<id>1</id>
<name>first</name>
</item>
<item>
<id>2</id>
<name>second</name>
</item>
<item>
<id>5</id>
<name>fifth</name>
</item>
</data>';
-- idoc is the xml representation we work with
EXEC sp_xml_preparedocument @idoc OUTPUT, @inputXml;
-- setup our table to merge
DECLARE @myTable TABLE (id int primary key, name varchar(50))
INSERT INTO @myTable (id, name)
VALUES
(1, 'one'),
(2, 'two'),
(3, 'three');
SELECT * FROM @myTable
-- merge the selected XML content into myTable
-- if we match on ID, update the name
-- if we don't find a match in the table, insert the entry in the XML
-- if we don't find a match in the XML, delete the entry in the table
MERGE INTO @myTable AS Target
USING
OPENXML(@idoc, 'data/item', 2)
WITH (id int 'id/text()', name nvarchar(50) 'name/text()')
AS source
ON Target.id = source.id
WHEN MATCHED THEN UPDATE SET name = source.name
WHEN NOT MATCHED BY TARGET THEN INSERT (id, name) VALUES (id, name)
WHEN NOT MATCHED BY SOURCE THEN DELETE;
SELECT * FROM @myTable