Select Into ##TempTable from C# DataTable

1.5k Views Asked by At

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

1

There are 1 best solutions below

0
Ubaid On

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