将SQL查询转换为VBA

时间:2018-06-12 05:39:53

标签: sql excel vba excel-vba

我在Oracle中成功运行了SQL查询,代码为 -

Select Sam.SAM_ID, sum( case when Aud.AUDIT_COMPLETION between (next_day(trunc(sysdate, 'iw'), 'Friday') -  14) and 
(next_day(trunc(sysdate, 'iw'), 'Friday') - 7) then 1 else 0 end ) as "Major Defects - 1 week",
 sum( case when Aud.AUDIT_COMPLETION between (next_day(trunc(sysdate, 'iw'), 'Friday') -  28) and (next_day(trunc(sysdate, 'iw'), 'Friday') - 7) then 1 else 0 end ) as "Major Defect - 4 week", count(Aud.AUDIT_COMPLETION)
From CMS.CMS_SAM_ALL_DATA Sam left join CMS.WATSON_AUDIT_INSPECTION_DT1_VW Aud ON Sam.SAM_ID = Aud.SAM_ID
Where Aud.DEFECT_SEVERITY = 'Major' AND 
Aud.AUD_RESULT = 'Defect' And 
NOT (Aud.AUDIT_OUTCOME = 'SPFR Withdrawn' and 
Aud.AUDIT_OUTCOME = 'Defect/ Observation Cancelled' and 
Aud.AUDIT_OUTCOME = 'Rejected by MIMA' and 
Aud.AUD_RESULT = 'Fixed' and 
Aud.AUDIT_OUTCOME = 'SPFR response accepted') and 
Aud.AUDIT_COMPLETION IS NOT NULL
Group by Sam.SAM_ID; 

现在我尝试在宏(VBA)中运行上面的代码但是无法成功运行宏,宏代码 -

StrSQL = StrSQL & "Select Sam.SAM_ID,"
 StrSQL = StrSQL & "sum(case when Aud.AUDIT_COMPLETION between (next_day(trunc(sysdate, 'iw'), 'Friday') - 14) and (next_day(trunc(sysdate, 'iw'), 'Friday') - 7) then 1 else 0 end )as ""Major Defects - 1 week"","
    StrSQL = StrSQL & "sum(case when Aud.AUDIT_COMPLETION between (next_day(trunc(sysdate, 'iw'), 'Friday') - 28) and (next_day(trunc(sysdate, 'iw'), 'Friday') - 7) then 1 else 0 end )as ""Major Defect - 4 week"","
    StrSQL = StrSQL & "count(Aud.AUDIT_COMPLETION)as ""Total Open Defects""
    StrSQL = StrSQL & "From CMS.CMS_SAM_ALL_DATA Sam left join CMS.WATSON_AUDIT_INSPECTION_DT1_VW Aud ON Sam.SAM_ID = Aud.SAM_ID"
    StrSQL = StrSQL & "Where Aud.DEFECT_SEVERITY = 'Major' AND Aud.AUD_RESULT = 'Defect' And NOT (Aud.AUDIT_OUTCOME = 'SPFR Withdrawn' and Aud.AUDIT_OUTCOME = 'Defect/ Observation Cancelled' and Aud.AUDIT_OUTCOME = 'Rejected by MIMA' and Aud.AUD_RESULT = 'Fixed' and Aud.AUDIT_OUTCOME = 'SPFR response accepted') and Aud.AUDIT_COMPLETION IS NOT NULL, Aud.AUDIT_COMPLETION IS NOT NULL, "
    StrSQL = StrSQL & "Group by Sam.SAM_ID;"

当我运行上面的代码时,我得到一个错误 -

  

从未找到预期的关键字

2 个答案:

答案 0 :(得分:2)

使用续行(_)并加倍引号以逃避它们:

strSQL = "select a, b as ""My Field"" from " & _
          "tableZ where a = 'blah' and " & _
          "b ='blah' "

答案 1 :(得分:0)

您在count(Aud.AUDIT_COMPLETION)From CMS.CMS_SAM_ALL_DATA Sam left

之间没有空间

但接受蒂姆威廉姆斯的建议并将其拆分为新线。你也可以这样做:

Dim strSQL As String

strSQL = strSQL & "SELECT "
strSQL = strSQL & "1 "
strSQL = strSQL & "FROM dual "