【发布时间】:2015-01-02 05:52:09
【问题描述】:
我有一个项目需要查询 Teradata 数据库,然后将返回的记录复制到 SQL Server 数据库。我可以毫无问题地访问 Teradata 数据库,并且可以将结果放入 DataTable。 SQL server db 已经设置好,并且具有与 Teradata 结果相同的列(auto id 列除外)。我无法弄清楚如何获取 DataTable 中的记录并将它们插入到 SQL 服务器数据库中。
这是我认为细节不相关的一些伪代码:
Using cn As New TdConnection("User Id=XYZ12345;Password=XYZ12345;Data Source=teradataserver.company.com;Persist Security Info=False")
cn.Open()
Dim cmd As TdCommand = cn.CreateCommand()
'build the SELECT part of the command we will issue
cmd.CommandText = GetTeradataSqlString()
'setup the DataAdapter
Dim da As New TdDataAdapter(cmd)
' Provider specific types will be used in the data table
da.ReturnProviderSpecificTypes = False 'True=Use Teradata types, False=Use .NET types
' Adapter will determine how many statements will be batched
da.UpdateBatchSize = 0
Dim cb As New TdCommandBuilder(da)
'create a DataTable to hold our returned data
Dim dtCheck As New DataTable("TableCheck")
' Filling the data table with data retrieved from the select statement
da.Fill(dtCheck)
'create a DataSet to hold all of our tables
Dim dsMain As New DataSet("MainDataset")
'now we add the DataTable to our DataSet
dsMain.Tables.Add(dtCheck)
'at this point a cycle through the DataTable to the debug window shows we have the data we need from the Teradata db.
'now we will pump it into our SQL server database
Dim connSqlSvr As New System.Data.SqlClient.SqlConnection
connSqlSvr.ConnectionString = "Data Source=DestSqlServer;Initial Catalog=DestDb;Connect Timeout=15"
connSqlSvr.Open()
'now we create a SQL command to take the data in the Teradata DataTable and insert it into the SQL server table
Dim sqlCmd As New SqlCommand
With sqlCmd
.CommandType = CommandType.Text
Dim sbSqlCmd As New StringBuilder
sbSqlCmd.AppendLine("INSERT INTO [DestDb].[dbo].[Events] ([CityCode],[CarNum],[VIN],[Fleet],[EventItm])")
sbSqlCmd.AppendLine("SELECT City,CarNo,VIN,Fleet,EventDesc FROM @MyTable;")
.CommandText = sbSqlCmd.ToString
Dim sqlParam As New SqlParameter
sqlParam.ParameterName = "@MyTable"
sqlParam.SqlDbType = SqlDbType.Structured
sqlParam.Value = dtCheck
sqlParam.TypeName = "TableCheck"
.Parameters.Add(sqlParam)
.Connection = connSqlSvr
Dim rowsAffectedLoad As Integer = .ExecuteNonQuery()
debug.print(rowsAffectedLoad & " rows were loaded into the SQL server table.")
End With
'close and dispose the SQL server database connection
connSqlSvr.Close()
connSqlSvr.Dispose()
End Using
运行代码我得到一个异常:
"Column, parameter, or variable @MyTable. : Cannot find data type TableCheck."
我一直在寻找一种将 DataTable 插入数据库的方法,并注意到许多示例都在使用 INSERT INTO。我只是认为我没有正确使用 SqlParameter。
【问题讨论】:
标签: sql-server vb.net ado.net teradata sql-insert