【问题标题】:Select Into ##TempTable from C# DataTable从 C# 数据表中选择进入##TempTable
【发布时间】:2016-04-22 17:16:08
【问题描述】:

我在 C# 中有一个 DataTable 变量,我想将它直接插入到 SQL 中的 ##TempTable 中。我不想像逐行插入 ##TempTable 一样。

我该怎么做?

Select Into ##TempTable from (C# DataTable) ?

或者我以不同的方式问:我们如何在 C# 的查询中将数据集发送到 SQL?

注意:我正在使用 SqlClient 和 SqlHelper 类

【问题讨论】:

标签: c# sql-server select datatable sqlhelper


【解决方案1】:

以防万一有人有同样的要求。欢迎任何评论。 VB中的代码。

Private Sub Connect(srcDT As DataTable, spParameter As String)
    Dim conString As String = GetConnectionString()

    Dim oSqlConnection As SqlConnection = New SqlConnection(conString)
    Try

        Dim oSqlCommand = New SqlCommand("Create Table #STG1 (
            [Username] [nvarchar](100) NULL,
            [FirstName] [nvarchar](100) NULL,
            [LastName] [nvarchar](100) NULL,
            [Active] [bit] NULL,
            [Department] [nvarchar](100) NULL
        )", oSqlConnection) With {
        .CommandType = CommandType.Text,
        .CommandTimeout = 0
    }
        oSqlConnection.Open()
        oSqlCommand.ExecuteNonQuery()
        Dim oSqlBulkCopy As SqlBulkCopy = New SqlBulkCopy(oSqlConnection) With {
        .DestinationTableName = "#STG1"
    }
        oSqlBulkCopy.WriteToServer(srcDT)

        Dim command As New SqlCommand("spName", oSqlConnection) With {
        .CommandType = CommandType.StoredProcedure
    }
        command.Parameters.AddWithValue("@inParam", spParameter)
        command.ExecuteScalar()

    Finally
        oSqlConnection.Close()
        oSqlConnection.Dispose()
    End Try

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 2015-07-12
    • 2021-12-02
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    相关资源
    最近更新 更多