1

我正在寻找完成以下任务的最佳方法的建议。我需要运行一个最多可以提取 200 行的 SQL 查询。对于每一行,我需要从该行获取数据并将其插入另一个表中。起初我以为我会像下面列出的代码示例那样嵌套数据库连接。但是,我想知道这是否是不正确的做法以及更好的方法。

有任何想法吗?

Dim dbconn As New SqlConnection
Dim dbconn2 As New SqlConnection
dbconn = New         SqlConnection(ConfigurationManager.ConnectionStrings("databaseName").ConnectionString
dbconn2 = New SqlConnection(ConfigurationManager.ConnectionStrings("databaseName").ConnectionString
dbconn.Open() 
Dim cmd As New SQLCommand
Dim cmd2 As New SQLCommand
Dim UserReader As SqlDataReader 

Dim cmdStringSource As String = "SELECT approx 25 fields WHERE fldRandomField = 26"
Dim cmdStringUpdate As String
cmd = New SQLCommnd(cmdStringSource, dbconn)
UserReader = cmdExecuteReader()
If UserReader.HasRows Then
While UserReader.Read()
    cmdStringUpdate = "UPDATE tblUpdate SET a whole bunch of stuff from the cmdStringSource current record"
    dbconn2.Open()
    cmd2=New SQLCommand(cmdStringUpdate, dbconn2)
    cmd2.ExecuteNonQuery()
    dbconn2.close()
End While
End If
UserReader.Close()
dbconn.close() 
4

1 回答 1

3

而不是在循环中使用多个连接和数据读取器执行此操作 - 完全在后端执行此操作。

SQL Server 支持从选择中插入,例如

INSERT INTO Table1 (field1, field2, field3 ...)
SELECT field1, field2, field3 FROM FROM Table2 
WHERE <some condition>

更新也是如此,例如

UPDATE Table1
  SET Table1.Field1 = Table2.Field1,
      Table1.Field2 = Table2.Field2
      Table1.Field3 = Table2.Field3
  FROM Table1 INNER JOIN Table2
  ON Table1.CommonField = Table2.CommonField
WHERE <some condition>

只需构建此语句并使用单个连接和ExecuteNonQuery命令调用它一次。

于 2013-08-05T15:16:23.067 回答