在vb6中针对SQLServer数据库的单个命令中执行多个SQL语句

时间:2015-10-14 10:03:28

标签: sql-server vb6 adodb

我正在尝试使用ADODB和vb6对SQL Server数据库执行多个SQL语句。

当我打开记录集时,代码会停止并显示以下错误代码:

运行时错误' 3704': 当对象关闭时,不允许操作。

这是我的代码:

Dim sql As String
sql = "WITH " & vbCrLf & _
      "q AS" & vbCrLf & _
      "(SELECT Item_No, Unit_OldQuantity" & vbCrLf & _
      "FROM dbo.The_Units),  sequenced AS" & vbCrLf & _
      "(SELECT ROW_NUMBER() OVER (PARTITION BY Item_No ORDER BY Unit_OldQuantity DESC) AS sequence_id,*" & vbCrLf & _
      "From q)" & vbCrLf & _
      "SELECT Item_No , Unit_OldQuantity" & vbCrLf & _
      "into #tmpTable" & vbCrLf & _
      "From sequenced" & vbCrLf & _
      "Where sequence_id = 1" & vbCrLf & _
      "SELECT sum(The_ItemDetails.Item_Cost / #tmpTable.Unit_OldQuantity * The_ItemDetails.Item_Quantity) AS Total" & vbCrLf & _
      "FROM  The_Items INNER JOIN The_ItemDetails ON The_Items.Item_No = The_ItemDetails.Item_No INNER JOIN #tmpTable ON The_ItemDetails.Item_No = #tmpTable.Item_No" & vbCrLf & _
      "Where the_items.Item_kind = 0"


Dim connText As String
connText = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=AlmohasebSQL;Data Source=server-pc\SQLEXPRESS"
Db_Almohaseb.ConnectionString = connText
Db_Almohaseb.Open
Dim RS_ItemDetails As New ADODB.Recordset
RS_ItemDetails.Open sql, Db_Almohaseb, adOpenStatic, adLockOptimistic, adCmdText
Text1.Text = RS_ItemDetails.RecordCount

我可以使用相同的连接运行任何其他sql语句,但不能使用此连接。 我也可以在.net中运行此命令,但不能在vb6中运行。 现在我只需要知道为什么会发生这种情况,而且我从头撞在桌子上感到恍惚。 请有人对此有所了解。

由于

2 个答案:

答案 0 :(得分:1)

当你有一个包含多个sql语句的sql语句时,你需要使用SET NOCOUNT ON,如下所示:

sql = "SET NOCOUNT ON;" & _
      "WITH " & vbCrLf & _
      "q AS" & vbCrLf & _
      "(SELECT Item_No, Unit_OldQuantity" & vbCrLf & _
      "FROM dbo.The_Units),  sequenced AS" & vbCrLf & _
      "(SELECT ROW_NUMBER() OVER (PARTITION BY Item_No ORDER BY Unit_OldQuantity DESC) AS sequence_id,*" & vbCrLf & _
      "From q)" & vbCrLf & _
      "SELECT Item_No , Unit_OldQuantity" & vbCrLf & _
      "into #tmpTable" & vbCrLf & _
      "From sequenced" & vbCrLf & _
      "Where sequence_id = 1" & vbCrLf & _
      "SELECT sum(The_ItemDetails.Item_Cost / #tmpTable.Unit_OldQuantity * The_ItemDetails.Item_Quantity) AS Total" & vbCrLf & _
      "FROM  The_Items INNER JOIN The_ItemDetails ON The_Items.Item_No = The_ItemDetails.Item_No INNER JOIN #tmpTable ON The_ItemDetails.Item_No = #tmpTable.Item_No" & vbCrLf & _
      "Where the_items.Item_kind = 0"

答案 1 :(得分:0)

我的问题唯一可用的解决方案是将语句移动到存储过程。 所以我检查目标数据库中是否存在该过程,如果不存在,我将创建该过程;否则,我用适当的参数执行程序。 我还包括用于检查临时文件的逻辑(如果它存在于db。

中)