使用XML对SQL SERVER数据库中数据进行批量修改
Bulk update the datas of SQL SERVER(2005 OR 2008) using XML
when we update data ,we firstly use the Class of StringBuilder to build the string of XML:
StringBuilder builder=new StringBuilder();
builder.Append("<root>");
builder.AppendFormat("<ID>{0}</ID>",ID.Text);
builder.AppendFormat("<dataName>{0}</dataName>",dataName.Text);
builder.AppendFormat("<UseName>{0}</UseName>",UseName.Text);
builder.Append("</root>");
Secondly,we create procedure in SQL :
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
create PROCEDURE [dbo].[Update....]
(
@XMLCustomer XML
)
AS
BEGIN
UPDATE Customer
SET CustName=TempCustomer.Item.value('@dataName', 'VARCHAR(50)'),
CustState=TempCustomer.Item.value('@UseName', 'VARCHAR(50)')
FROM @XMLCustomer.nodes('/root/row') AS TempCustomer(Item)
WHERE ID=TempCustomer.Item.value('@ID', 'INT')
RETURN 0
END
Thirdly:T_SQL FOR Operate SQL DataBase
........
........
Test:
declare @data xml
set @data='<Tags><Tag><HouseID>13c099d2-1378-41cd-8266-22537efe0ff3</HouseID></Tag><Tag><HouseID>2AB284E4-9315-4AE5-B325-AF09AE423320</HouseID></Tag><Tag><HouseID>D1B3BB46-DD65-4830-85E9-6CB87108B2EF</HouseID></Tag></Tags>'
--修改House表的ISEnable为0
SELECT
T.V.value('HouseID[1]','UNIQUEIDENTIFIER') as HouseID
INTO #TagsReport
FROM @data.nodes('//Tags/Tag') AS T(V)
UPDATE dbo.tb_HCS_House
SET ISEnable=0
from dbo.tb_HCS_House tb_h
left join #TagsReport as rep on rep.HouseID=tb_h.HouseID
WHERE rep.HouseID is not null
DROP TABLE #TagsReport