如何构造XML并将其作为参数传递给MS SQL 2005服务器上的存储过程?您如何将INSERT
XML转换为表格?
数据采用键/值对的形式:
[
0: [key, value],
1: [key, value],
2: [key, value]
]
答案 0 :(得分:16)
以下是一个例子:
/* Create the stored procedure */
create procedure ParseXML (@InputXML xml)
as
begin
declare @MyTable table (
id int,
value int
)
insert into @MyTable
(id, value)
select Row.id.value('@id','int'), Row.id.value('@value','int')
from @InputXML.nodes('/Rows/Row') as Row(id)
select id, value
from @MyTable
end
go
/* Create the XML Parameter */
declare @XMLParam xml
set @XMLParam = '<Rows>
<Row id="1" value="100" />
<Row id="2" value="200" />
<Row id="3" value="300" />
</Rows>'
/* Call the stored procedure with the XML Parameter */
exec ParseXML @InputXML = @XMLParam
/* Clean up - Drop the procedure */
drop procedure ParseXML
go
答案 1 :(得分:0)
我通过ajax请求操作方法发送了一个用逗号分隔的用户ID字符串。
public ActionResult EnableSelectedUser(string userIds)
{
List<int> users = new List<int>();
我将逗号分隔的ID字符串转换为列表。
var userList = userIds.TrimEnd(',').Split(',').ToList();
foreach (var u in userList)
{
var data = new NotificationUsers()
{
UserId = Int32.Parse(u)
};
users.Add(data);
}
已将列表转换为xml
string xml = UBConvert.ListToXML(users, "DS", "DT");
将列表转换为xml的方法
public static string ListToXML(object list, string dataSetName, string dataTableName,
StringCollection fieldNames)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
var ds = new DataSet { Locale = CultureInfo.InvariantCulture };
ds.Tables.Add(GenericListToDataTable(list, fieldNames));
ds.DataSetName = dataSetName;
ds.Tables[0].TableName = dataTableName;
return ds.GetXml();
}
将xml作为参数传递给存储过程
Parameter[] lstParams = new Parameter[]
{
new Parameter("@CurrentUserId", currentUserId),
new Parameter("@Xml", xml)
};
return UBConvert.ToInt32(DataBaseHelper.ExecuteScalar("Admin_EnableBulkUser", lstParams));
接受xml作为参数的存储过程
CREATE PROCEDURE [dbo].[Admin_EnableBulkUser]
(
@CurrentUserId INT = 0,
@Xml xml
)
AS
BEGIN
DECLARE @Result INT = -1
DECLARE @Users table (UserId int, RowId int)
INSERT INTO @Users(UserId)
Select
T.Item.value('UserId[1]','int')
from @Xml.nodes('//DS/DT') AS T(Item)
BEGIN TRY
BEGIN TRAN
UPDATE dbo.[User]
SET UserStatus = 1,
DeletedBy = @CurrentUserId,
DeletedOn = GETUTCDATE(),
SyncStatus = 0
FROM dbo.[User] u INNER JOIN @Users us on u.UserId = us.UserId
set @Result =1
select @Result;
COMMIT
SELECT @Result
END TRY
BEGIN CATCH
ROLLBACK
Select @Result =0;
END CATCH
END