代码之家  ›  专栏  ›  技术社区  ›  punkouter

将数据表传递到存储过程中。有更好的方法吗?

  •  3
  • punkouter  · 技术社区  · 15 年前

    数据表能否以某种方式传递到SQL Server 2005或2008中?

    我知道Seesm将XML传递到SP的标准方法,并且数据表可以很容易地转换为XML来实现这一点。

    将.NET对象传递到SP中怎么样?有可能吗?

    我记得在2008年听说过SQL和CLR一起工作,但我从来都不明白……也许这意味着您可以引用存储过程中的.NET对象?

    2 回复  |  直到 11 年前
        1
  •  8
  •   Paul Kearney - pk    15 年前

    可以在SQL中创建用户定义的表类型。然后,在存储过程中,接受类型为(用户定义的表类型)的参数,并将其值传递给存储过程。

    以下是一些例子 http://msdn.microsoft.com/en-us/library/bb675163.aspx :

    在SQL中:

    CREATE TYPE dbo.CategoryTableType AS TABLE
        ( CategoryID int, CategoryName nvarchar(50) )
    

    然后:

    // Assumes connection is an open SqlConnection object.
    using (connection)
    {
    // Create a DataTable with the modified rows.
    DataTable addedCategories =
      CategoriesDataTable.GetChanges(DataRowState.Added);
    
    // Configure the SqlCommand and SqlParameter.
    SqlCommand insertCommand = new SqlCommand(
        "usp_InsertCategories", connection);
    insertCommand.CommandType = CommandType.StoredProcedure;
    
    SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
        "@tvpNewCategories", addedCategories);
    tvpParam.SqlDbType = SqlDbType.Structured;
    
    // Execute the command.
    insertCommand.ExecuteNonQuery();
    }
    
        2
  •  0
  •   jidh    11 年前

    否则,您可以选择SQL大容量插入。

    我试过了,最好的方法。

    enter code here
    
      Using dbConn As New SqlConnection(connectionStr)
                    dbConn.Open()
                    countStart = System.Convert.ToInt32(commandRowCount.ExecuteScalar())
    
    
    
                    Using bulkcopy As SqlBulkCopy = New SqlBulkCopy(dbConn)
                        bulkcopy.DestinationTableName = "[dbo].[DocumentScan]"
                        Try
                            ' Write from the source to the destination.
                            bulkcopy.WriteToServer(newDataTable)
    
                        Catch ex As Exception
                            Console.WriteLine(ex.Message)
                        End Try
                        Dim countEnd As Long = _
                      System.Convert.ToInt32(commandRowCount.ExecuteScalar())
    
    
                    End Using