[英]Passing datatable to a stored procedure
我有一個用C#創建的數據表。
using (DataTable dt = new DataTable())
{
dt.Columns.Add("MetricId", typeof(int));
dt.Columns.Add("Descr", typeof(string));
dt.Columns.Add("EntryDE", typeof(int));
foreach (DataGridViewRow row in dgv.Rows)
{
dt.Rows.Add(row.Cells[1].Value, row.Cells[2].Value, row.Cells[0].Value);
}
// TODO: pass dt
}
我有一個存儲過程
CREATE PROCEDURE [dbo].[Admin_Fill]
-- Add the parameters for the stored procedure here
@MetricId INT,
@Descr VARCHAR(100),
@EntryDE VARCHAR(20)
我想要的是將數據表傳遞給這個存儲過程,怎么樣?
從SQL Server 2008 / .NET 3.5開始,您可以使用表值參數....
查看MSDN上的指南
此外,由於還有其他可用選項,我比較了3種將多個值(單個字段)傳遞給sproc的方法( TVP vs XML vs CSV )
您需要定義要在數據庫中的用戶定義表類型中傳遞的表類型 。
然后,您需要在存儲過程中添加參數以將其傳遞為:
@YourCustomTable AS [dbo].YourCustomTable Readonly,
然后,當您設置行時,請按以下方式調用它:
// Setup SP and Parameters command.CommandText = "YOUR STORED PROC NAME"; command.Parameters.Clear(); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@someIdForParameter", someId); command.Parameters.AddWithValue("@YourCustomTable",dtCustomerFields).SqlDbType = SqlDbType.Structured; //Execute command.ExecuteNonQuery();
這應該可以解決您的問題
我們通常將數據噴射到XML文檔中,並將數據作為NTEXT參數傳遞給數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.