我需要通过ADO.NET创建临时表,在temp和实际表之间的服务器上执行BulkCopy
然后Merge
。
问题是使用纯ADO.NET创建临时表动态。 模式应该与现有表相同,但是这个表是使用ORM(NHibernate或实体框架,我们还不确定)创建的。这也意味着架构将来可能会发生变化。
有没有办法使用普通的ADO.NET对象在数据库中创建表?比如包含原始表格架构的DataTable
?
任何指向正确方向的信息都会受到赞赏。
答案 0 :(得分:3)
您可以使用select into #somename创建临时表。
connection_ = New SqlClient.SqlConnection(connection_string_)
connection_.Open()
If connection_.State = ConnectionState.Open Then
command_.Connection = connection_
command_.CommandType = CommandType.Text
command_.CommandText = "select * into #some_table from some_table where some_id = 0"
command_.ExecuteNonQuery()
Dim line_index_ As Integer = 0
Dim data_table_ As DataTable = New DataTable()
Using parser_ As FileIO.TextFieldParser = New FileIO.TextFieldParser(path_)
parser_.SetDelimiters(delimiter_)
parser_.HasFieldsEnclosedInQuotes = False
While Not parser_.EndOfData
If line_index_ = 0 Then
Dim headers_ As String() = parser_.ReadFields()
For Each header_ In headers_
data_table_.Columns.Add(header_)
Next
Else
Dim row_ As DataRow = data_table_.NewRow()
row_.ItemArray = parser_.ReadFields()
data_table_.Rows.Add(row_)
End If
line_index_ += 1
End While
End Using
Using bulkCopy_ As SqlBulkCopy = New SqlBulkCopy(connection_)
bulkCopy_.DestinationTableName = "#some_table"
bulkCopy_.WriteToServer(data_table_)
End Using
' proof
command_.CommandText = "select * from #some_table"
Dim reader_ As SqlDataReader = Nothing
reader_ = command_.ExecuteReader
line_index_ = 0
While reader_.Read
line_index_ += 0
End While
End If
答案 1 :(得分:2)
我设法根据现有架构创建临时表。