0

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

3

1 Answer 1

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.