![](/img/trans.png)
[英]How to bind GridView to the Database and perform Update/Insert operations
[英]In genric list values passing to xml . How to perform Insert and update operations sql?
場景:1.Form具有5條記錄的gridview。 (綁定來自數據庫的記錄)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
這是使用SQL MERGE的理想選擇。 它使您可以在單個語句中根據匹配條件插入/更新/刪除。
檢查Microsoft Technet參考以獲取更多信息。
編輯:這是與OPENXML一起使用SQL MERGE的一些示例代碼
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.