2

我正在尝试在电子表格的特定空间中写入查询结果。SQL 创建临时表以在查询期间使用,然后在最后删除它们。这是我的问题的原因吗?我在下面发布了我的源代码。错误在第 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
4

2 回答 2

1

快速浏览一下,我会尝试这种方法:

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

...然后插入您的 SQL(记住icd9_poa已经定义)

    END

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

我无法完全测试它,因为我没有您的数据,但这是一种从 SQL 过程返回记录集的方法。

于 2012-12-03T14:38:26.630 回答
0

删除临时表不是必需的,也不会导致您的错误。

在您调用“CopyFromRecordSet”时,您的连接似乎已关闭,请尝试将该调用移至“With”块。

于 2012-11-27T02:30:35.500 回答