对象closures时不允许操作 – 在第一行创build表语句?

我正在试图在电子表格的特定空间中写入查询的结果。 SQL在查询过程中创build临时表,然后在最后删除它们。 这是我的问题的原因? 我已经在下面发布了我的源代码。 错误在530行被抛出。有没有更好的方法来做到这一点?

410 With wsSheet 420 Set rnStart = Sheets("Discharge Information").Range("Q51") 430 End With 440 strSQL = "create table #encounters ( DischargeKey int,EncounterID varchar(25)) insert into #encounters " & _ "SELECT top 30 dischargekey,encounternumber from discharges order by dischargedate desc " & _ "CREATE TABLE #icd9_poa(DischargeKey int,ICD9 nvarchar(max),POA nvarchar(max)) " & _ "DECLARE @i int, @f int SET @i = 1 SET @f = ( " & _ "SELECT REPLACE(column_name,'icd9_POA_','') FROM information_schema.Columns WHERE column_name LIKE 'icd9_POA_%' AND table_name = 'temp_discharge' AND ordinal_position IN ( " & _ "SELECT Max (ordinal_position) FROM information_schema.Columns " & _ "WHERE column_name LIKE 'icd9_POA_%' AND table_name = 'temp_discharge')) " & _ "WHILE @i <= @f " & _ "BEGIN IF @i=1 " & _ "BEGIN INSERT INTO #icd9_poa " & _ "SELECT d.DischargeKey,i.icd9code,poa.poa " & _ "FROM discharges d " & _ "inner join #encounters e on e.dischargekey = d.dischargekey INNER join icd9diagnosesbridge icb on icb.discharge=d.dischargekey INNER join icd9diagnoses i on icb.icd9 = i.icd9key INNER join presentonadmission poa on icb.presentonadmission = poa.poakey " & _ "WHERE icb.Icd9Sequence = 1 End " & _ "IF @I>1 BEGIN " & _ "Update t SET t.Icd9 = t.Icd9 + ', '+i.Icd9Code,t.poa = t.poa + ', '+ poa.poa " & _ "FROM #Icd9_poa t" & _ "INNER JOIN Discharges d ON (t.DischargeKey=d.DischargeKey) INNER JOIN Icd9DiagnosesBridge icb ON (icb.Discharge=d.DischargeKey) INNER JOIN Icd9Diagnoses i ON (icb.Icd9=i.icd9Key) INNER JOIN PresentOnAdmission poa ON (icb.PresentOnAdmission=poa.PoaKey) " & _ "WHERE icb.Icd9Sequence=@i End " & _ "SET @i = @i + 1 End " & _ "select icd9, poa from #icd9_poa " & _ "drop table #icd9_poa " & _ "drop table #encounters " 450 Set cnt = New ADODB.Connection 460 470 With cnt 480 .CursorLocation = adUseClient 490 .Open ConnectionString 500 .CommandTimeout = 0 510 Set rst = .Execute(strSQL) 520 End With 530 rnStart.CopyFromRecordset rst 

很快,我会试试这个方法:

 RETURNS @icd9_poa TABLE ( DischargeKey int, ICD9 nvarchar(max), POA nvarchar(max)) AS BEGIN 

…然后插入你的SQL(记住icd9_poa已经定义)

  END 

不要担心删除临时表 – SQL Server会在您的过程完成运行后立即删除它们

我不能完全testing它,因为我没有你的数据,但这是从SQL过程返回logging集的方法。

删除临时表是不必要的,不会导致你的错误。

看起来您的连接在您调用“CopyFromRecordSet”时已closures,请尝试将该调用移入“With”块。