从两个逗号分隔的参数更新一个表作为输入 [英] Update a table from two comma separated parameter as input
问题描述
我有一个Gridview在前端,其中Grid有两列:ID和Order这样:
I have a Gridview in front end where Grid have two columns : ID and Order like this:
ID Order
1 1
2 2
3 3
4 4
现在用户可以像前端Gridview一样更新订单:
Now user can update the order like in front end Gridview:
ID Order
1 2
2 4
3 1
4 3
现在,如果用户点击保存按钮,ID和订单数据被发送到存储过程作为@sID =(1,2,3,4)和@sOrder =(2,4,1,3)
Now if the user click the save button the ID and order data is being sent to Stored Procedure as @sID = (1,2,3,4) and @sOrder = (2,4,1,3)
现在如果我想更新订单并进行保存,我想将其存储到数据库中。通过存储过程如何更新到表中,以便表更新,而选择它给我的结果像:
Now if I want to update the order and make save I want to store it into database. Through Stored procedure how can update into the table so that the table is updated and while select it gives me the results like:
ID Order
1 2
2 4
3 1
4 3
推荐答案
您可以使用表值参数,以避免将定界符分隔值或甚至XML发送到数据库。为此,您需要:
You could use a table valued parameter to avoid sending delimiter-separated values or even XML to the database. To do this you need to:
-
在数据库中声明参数类型,如下所示:
Declare a parameter type in the database, like this:
CREATE TYPE UpdateOrderType TABLE (ID int, Order int)
之后,您可以定义将参数用作
After that you can define the procedure to use the parameter as
CREATE PROCEDURE UpdateOrder (@UpdateOrderValues UpdateOrderType readonly)
AS
BEGIN
UPDATE t
SET OrderID = tvp.Order
FROM <YourTable> t
INNER JOIN @UpdateOrderValues tvp ON t.ID=tvp.ID
END
使用C#中的参数:
using (SqlCommand command = connection.CreateCommand()) {
command.CommandText = "dbo.UpdateOrder";
command.CommandType = CommandType.StoredProcedure;
//create a table from your gridview data
DataTable paramValue = CreateDataTable(orderedData)
SqlParameter parameter = command.Parameters
.AddWithValue("@UpdateOrderValues", paramValue );
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "dbo.UpdateOrderType";
command.ExecuteNonQuery();
}
其中 CreateDataTable
例如:
//assuming the source data has ID and Order properties
private static DataTable CreateDataTable(IEnumerable<OrderData> source) {
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Order", typeof(int));
foreach (OrderData data in source) {
table.Rows.Add(data.ID, data.Order);
}
return table;
}
(代码从此问题)
正如你所看到的,这种方法(特定于SQL Server 2008和更高版本)使结构化数据作为参数传递到过程变得更容易和更正式。更重要的是,你一直在使用类型安全,所以很多在字符串/ xml操作中出现的解析错误不是问题。
As you can see this approach (specific to SQL-Server 2008 and up) makes it easier and more formal to pass in structured data as a parameter to a procedure. What's more, you're working with type safety all the way, so much of the parsing errors that tend to crop up in string/xml manipulation are not an issue.
这篇关于从两个逗号分隔的参数更新一个表作为输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!