我想从ASP VBscript查询SQL Server 2008 R2时从结果集中获取记录数:
Conn = "Provider=SQLNCLI10; DataTypeCompatibility=80; Data Source=Source; Initial Catalog=catalog; User ID=id; Password=pw; Network Library=dbmssocn; Encrypt=Yes;"
这将返回正确的记录计数:
consulta = "select 'x' x;"
rs.open consulta, Conexao, 3
Response.Write(rs.RecordCount)
但是当我从临时表中选择它时会抛出一个错误:
consulta = "select 'x' x into #t; select * from #t; drop table #t;"
rs.open consulta, Conexao, 3
Response.Write(rs.RecordCount)
ADODB.Recordset error '800a0e78'
Operation is not allowed when the object is closed.
答案 0 :(得分:3)
我认为你需要使用.NextRecordSet()
:
strsql = "select 'x' x into #t; select * from #t; drop table #t;"
rs.Open strsql, conn
'Move to your 2nd recordset to return the values (in this case 'x')
Set rs = rs.NextRecordset()
if not rs.eof then
response.write rs(0)
end if
rs.close
如果我将sql字符串分开并根据需要使用EXECUTE
或OPEN
,这对我也有用:
'Create Temp Table
strsql = "select 'x' x into #t; "
conn.execute strsql
'Select From Temp Table
strsql = "select * from #t;"
rs.open strsql, conn
if not rs.eof then
response.write rs(0)
end if
rs.close
'Drop Temp Table
strsql = "drop table #t;"
conn.execute strsql
希望这有帮助。
答案 1 :(得分:0)
如果问题只是复合SQL命令语句之一(在我的示例中使用临时表),那么这是一个非常通用的解决方案:
Set RecSet = CreateObject("ADODB.Recordset")
On Error Resume Next
Call RecSet.Open(SQLstr, ADO_ConnObj, adOpenStatic, adLockOptimistic)
ErrNum = Err.Number 'Capture it for later error processing
ErrDesc = Err.Description ' "
Do While ErrNum = 0 And RecSet.State <> adStateOpen
'SQL specifications that include use of local temporary tables (subsequently referenced by
'a final SELECT statement) are an example of compound command statements for which ADO
'returns a collection of record sets, one for each command statement in the specification.
'Local temporary tables are automatically dropped when they go out of scope, resulting in
'their corresponding record set's State property being set to adStateClosed, once the query
'is finished executing. So any such closed record sets must be ignored and skipped over,
'in order to find the actual query-results data, which will usually be the last record set
'in the collection, with a State property value of adStateOpen. So search for the first
'open record set:
Set RecSet = RecSet.NextRecordset
If RecSet Is Nothing Then
MsgBox "No open ADO DB Recordsets found in the returned Recordset collection."
Exit Sub
End If
Loop
On Error GoTo 0
'Process the actual data (or error conditions)...