gpt4 book ai didi

asp.net - 我可以将列表传递给存储过程吗?

转载 作者:行者123 更新时间:2023-12-02 07:42:40 26 4
gpt4 key购买 nike

我有以下列表

ID | DESC | PRICE 
10 | SHOE | 5000
11 | LACE | 3000
12 | GAME | 2000
13 | TOAD | 3000

我现在在 foreach 循环中传递单独的行,并一直建立一个新连接,这看起来很不传统,但我希望有更快的方法。

这是我的代码。

foreach(var item in tempList)
{
using (connection)
{
SqlCommand command = new SqlComman("StoredProc", connection);
command.Parameters.Add(new SqlParameter("id", item.id));
command.Parameters.Add(new SqlParameter("desc", item.desc));
command.Parameters.Add(new SqlParameter("price", item.price));
...
}
}

那么如何将列表传递给存储过程呢?

最佳答案

除了链接(绝对值得一读)之外,还提供了 TVP 的实际示例。假设 SQL Server 2008 或更高版本。

首先,在 SQL Server 中:

CREATE TYPE dbo.Items AS TABLE
(
ID INT,
Description VARCHAR(32),
Price INT
);
GO

CREATE PROCEDURE dbo.StoredProcedure
@Items AS dbo.Items READONLY
AS
BEGIN
SET NOCOUNT ON;

INSERT INTO dbo.DestinationTable(ID, [DESC], Price)
SELECT ID, Description, Price FROM @Items;
END
GO

现在在 C# 中:

DataTable tvp = new DataTable();
tvp.Columns.Add(new DataColumn("ID"));
tvp.Columns.Add(new DataColumn("Description"));
tvp.Columns.Add(new DataColumn("Price"));

foreach(var item in tempList)
{
tvp.Rows.Add(item.id, item.desc, item.price);
}

using (connection)
{
SqlCommand cmd = new SqlCommand("StoredProcedure", connection);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvparam = cmd.Parameters.AddWithValue("@Items", tvp);
tvparam.SqlDbType = SqlDbType.Structured;
connection.Open();
cmd.ExecuteNonQuery();
}

关于asp.net - 我可以将列表传递给存储过程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9402296/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com