从C#DataTable中选择Into ## TempTable

时间:2016-01-17 14:24:49

标签: c# sql-server select datatable sqlhelper

我在C#中有一个DataTable变量,我想在SQL Directly中将它插入到## TempTable中。我不想像往常一样插入## TempTable。

我该怎么做?

从(C#DataTable)中选择进入## TempTable?

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

注意:我使用的是SqlClient和SqlHelper类

1 个答案:

答案 0 :(得分:0)

以防万一有人有相同的要求。欢迎任何评论。 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