简体   繁体   中英

Select Into ##TempTable from C# DataTable

I have a DataTable varriable in C# and I want to insert it to a ##TempTable in SQL Directly. I dont want to do like insert into ##TempTable row by row.

How can I do that ?

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

Or I m asking in a different way: how can we send a dataset to SQL in a Query from C#?

Note: I m using SqlClient, and SqlHelper classes

Just in case anyone has the same requirement. Any comment is welcome. Code in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM