【问题标题】:how to pass datatable parameter to stored procedure sql server?如何将datatable参数传递给存储过程sql server?
【发布时间】:2014-03-23 22:46:01
【问题描述】:

我需要将数据表传递给下面的存储过程

 create procedure insert_data
(@a int ,
@b DataTable)
as 
Begin 
......
end

我使用 C#

【问题讨论】:

    标签: sql-server stored-procedures datatable


    【解决方案1】:

    您需要做几件事来完成这项工作,因为您想将表作为参数传递,您需要创建 (1) 表类型和 (2) 让您的存储过程接受该参数输入。

    以下是创建 TABLE TYPE 所需的步骤。

    表格类型

    CREATE TYPE dbo.DataTable AS TABLE 
     (
        -- define table structure here
      )
     GO
    

    程序

    现在让您的过程接受该表类型的参数。

    create procedure insert_data
    @a int ,
    @b dbo.DataTable READONLY    --<-- Note this is read only param
    as 
    Begin 
    ......
    end
    

    此传递的参数将是只读参数,因此如果您需要操作此参数中传递的值,您需要在您的过程中的表变量或临时表中获取这些值,然后才能进行任何更新或插入对它们进行操作。

    使用 C#

    您可以使用 DataTable 类创建一个与您在 sql server 中的表类型匹配的类型的新实例。像这样..

    DataTable dt = new DataTable("DataTable"); 
    
    // Add columns to this object same as the type in sql server
    
    dt.Columns.Add("Column1", typeof(string)); 
    dt.Columns.Add("Column2", typeof(Int32)); 
    
    //Populate the dt object 
    
    dt.Rows.Add("Value1", 1); 
    dt.Rows.Add("Value2", 2); 
    dt.Rows.Add("Value2", 3); 
    

    【讨论】:

    • sql的数据类型是什么?比如sqltype.string,,什么表的类型
    • @user3409439 - datatype 将依赖于您在数据库中命名的 type。在这种情况下,它将是 dbo.DataTable
    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 2015-12-20
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 2014-08-29
    相关资源
    最近更新 更多