【问题标题】:Pass List parameters to SQL Server stored procedure将列表参数传递给 SQL Server 存储过程
【发布时间】:2012-08-26 17:57:12
【问题描述】:

我是 c# 和 .Net 的新手,我需要你的帮助。

我在数据库中创建了一个接受表值参数(id 列表)的过程,并且我正在寻找适合 Oracle 关联数组的等价物。

--数据库中的新数据类型:

CREATE TYPE IDType AS TABLE
(
        ID bigint  
)
GO



-- DB Procedure
Create procedure TVP_PROC (@ID IDType readonly)
    Declare @TVP IDType
    Insert into @TVP select ID from @ID
As
  Update  my_tbl set id=(select ID from @TVP)

它应该像这样运行: exec TVP_PROC @ID //@ID is alist of id's

.Net 代码:

Public void UpdateID (List long<long> IDS )
{
    Datatable datatable = new datatable ();
    Datatable.columns.add (“IDS”,typeof(int64));
    Foreach (int64 id in IDS)
    {
        Datatable.Rows.Add(id);
    }
}


Var Query =hibernate.createsqlquery(“Exec TVP_PROC @ID:IDS”);

查询。 ??????

问题:

  1. 除了使用数据表变量并在每次迭代时分配 id 之外,还有其他首选的编写方式吗?

  2. 更重要的是,分配 table\list 变量的适当方法是什么?是否有任何表值\数组变量可以定义为这种数据类型?

【问题讨论】:

  • 现在是 2012 年,带有表值参数。
  • 非常感谢,效果很好!!!

标签: c# sql-server-2012


【解决方案1】:

现在您已经在数据库中创建了表类型和存储过程,在 C# 中,您需要这样的代码:

// define connection and command object
using(SqlConnection conn = new SqlConnection("your-connection-string-here"))
using(SqlCommand cmd = new SqlCommand("dbo.TVP_PROC", conn))
{
   // define the command to be a stored procedure
   cmd.CommandType = CommandType.StoredProcedure;

   // set up parameters
   cmd.Parameters.Add("@ID", SqlDbType.Structured).Value = datatable;

   // open connection, execute stored procedure, close connection
   conn.Open();
   cmd.ExecuteNonQuery();
   conn.Close();
}

【讨论】:

    【解决方案2】:
        Datatable datatable = new datatable ();
        Datatable.columns.add (“IDS”,typeof(int64));
        Foreach (int64 id in IDS)
        {
            Datatable.Rows.Add(id);
        }
    
     // Configure the SqlCommand and table-valued parameter.
     SqlCommand insertCommand = new SqlCommand("TVP_PROC", connection);
    
     insertCommand.CommandType = CommandType.StoredProcedure;
    
     //pass here your datatable
     SqlParameter tvpParam = insertCommand.Parameters.AddWithValue("@ID", datatable);
    
     //specify type of your parameter
     tvpParam.SqlDbType = SqlDbType.Structured;
    
      // Execute the command.
      insertCommand.ExecuteNonQuery();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-26
      • 2015-12-20
      • 2013-07-06
      • 2017-02-19
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      相关资源
      最近更新 更多