将数据集传递给存储过程

Passing DataSet to Stored Procedure

我有以下存储过程接收 DataSet 作为参数并插入 table Excel.

CREATE PROCEDURE spInsertInvoice
      @tblInvoice InvoiceType READONLY
AS
BEGIN
      SET NOCOUNT ON;

      INSERT INTO Excel
      SELECT Template, Cust_Name, Invoice_No,InvoiceDate FROM @tblInvoice
END

在我的代码文件中,我试图读取 Excel Sheet 并填充数据集。但问题是我对如何将 DataSet 作为 Parameter 发送到 stored Procedure 有点困惑。 这是我目前尝试过的方法,但似乎不起作用

if (FileUpload1.HasFile)
        {
            string path = string.Concat((Server.MapPath("~/temp/" + FileUpload1.FileName)));
            FileUpload1.PostedFile.SaveAs(path);
            OleDbConnection oleCon = new OleDbConnection("Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + path + ";Extended Properties = Excel 12.0;");
            OleDbCommand Olecmd = new OleDbCommand("select * from [Sheet1$]", oleCon);
            OleDbDataAdapter dtap = new OleDbDataAdapter(Olecmd);
            DataSet ds = new DataSet();
            dtap.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
            if (ds.Tables[0].Rows.Count > 0)
            {
                string consString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(consString))
                {
                    using (SqlCommand cmd = new SqlCommand("spInsertInvoice"))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Connection = con;
                        cmd.Parameters.AddWithValue("@tblInvoice", ds);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }
            }

当我执行它时,它会在 cmd.ExecuteNonQuery()

上抛出 ArgumentException

No mapping exists from object type System.Data.DataSet to a known managed provider native type.

您无法参数化您的 table 名称,基本上

参数化 SQL 仅用于值 - 不用于 table 名称、列名或任何其他数据库对象。这是您可能想要动态构建 SQL 的地方 - 但在将此 table 名称放入 sql 查询之前使用一组白名单选项或强验证。

就是那一行;

cmd.Parameters.AddWithValue("@tblInvoice", ds);

您尝试将您的 DataSet 传递给您的 table 名字,这没有意义。

您不能将数据集传递给存储过程,但可以将数据table传递给存储过程。按照以下算法执行它:

1) Create Table type in sql server for the DataTable which you want to pass.
2) Declare input variable for given table type as readonly in stored procedure.
3) Pass that data table to procedure.

这只限制你的table类型参数顺序和数据table列顺序应该相同。

你可以参考这个linkSending a DataTable to a Stored Procedure

Table-Valued Parameters