访问SQL到T-SQL

时间:2017-07-28 17:43:23

标签: sql-server tsql ms-access

此查询适用于MS Access:

SELECT 
       Firm.Adm_Firm_ID, 
       Firm.CCIS_Firm_Seqn_Nbr, 
       Firm.Firm_Name, 
       Firm.Dba_Firm_Name, 
       OHA.File_Closure_Date, 
       OHA.Adm_Qual_Flag,
       OHA.Firm_FY_End_Date,
       OHA.Report_Received_Date,
       OHA.Cognizant_Letter_Flag, 
       OHA.Audit_Type, 
       Firm.AQ_Flag,
       IIF(OHA.File_Closure_Date>=DATEADD("m", -18, Date()),"Yes","No") AS Relevant
FROM 
      dbo_Adm_Firm AS Firm 
INNER JOIN 
      dbo_Adm_OHA_Rate AS OHA ON Firm.Adm_Firm_ID = OHA.Adm_Firm_ID
WHERE 
      ((OHA.File_Closure_Date IS NOT Null) AND (OHA.File_Closure_Date>#1/1/2010#))
ORDER BY 
      Firm.Firm_Name, OHA.Firm_FY_End_Date DESC;

我尽力将其转换为T-SQL,我在批处理脚本中调用它。

SELECT 
      Firm.Adm_Firm_ID, 
      Firm.CCIS_Firm_Seqn_Nbr, 
      Firm.Firm_Name, 
      Firm.Dba_Firm_Name, 
      OHA.File_Closure_Date, 
      OHA.Adm_Qual_Flag, 
      OHA.Firm_FY_End_Date, 
      OHA.Report_Received_Date, 
      OHA.Cognizant_Letter_Flag, 
      OHA.Audit_Type, 
      Firm.AQ_Flag, 
      IIF(OHA.File_Closure_Date>=DATEADD(m, -18, GETDATE()),'Yes','No') AS Relevant
FROM 
      dbo.Adm_Firm AS Firm 
INNER JOIN 
      dbo.Adm_OHA_Rate AS OHA ON Firm.Adm_Firm_ID = OHA.Adm_Firm_ID
WHERE 
      ((OHA.File_Closure_Date IS NOT Null) AND (OHA.File_Closure_Date>'1/1/2010'))
ORDER BY 
      Firm.Firm_Name, OHA.Firm_FY_End_Date DESC;

我在excel文件中得到的输出是:

  

消息102,级别15,状态1,服务器CH-IS-DB1,行3   “'>'。

附近的语法不正确

所以我认为问题出在DATEADD方法中,但我无法弄清楚区别是什么。我尝试将Date()更改为GetDate()并更改字符串分隔符。有什么提示吗?

1 个答案:

答案 0 :(得分:1)

尝试使用CASE WHEN

SELECT 
      Firm.Adm_Firm_ID, 
      Firm.CCIS_Firm_Seqn_Nbr, 
      Firm.Firm_Name, 
      Firm.Dba_Firm_Name, 
      OHA.File_Closure_Date, 
      OHA.Adm_Qual_Flag, 
      OHA.Firm_FY_End_Date, 
      OHA.Report_Received_Date, 
      OHA.Cognizant_Letter_Flag, 
      OHA.Audit_Type, 
      Firm.AQ_Flag, 
      CASE 
      WHEN OHA.File_Closure_Date >= DATEADD(m, -18, GETDATE()) THEN 'Yes'ELSE 'No' END AS Relevant
FROM 
      dbo.Adm_Firm AS Firm 
INNER JOIN 
      dbo.Adm_OHA_Rate AS OHA ON Firm.Adm_Firm_ID = OHA.Adm_Firm_ID
WHERE 
      ((OHA.File_Closure_Date IS NOT Null) AND (OHA.File_Closure_Date>'1/1/2010'))
ORDER BY 
      Firm.Firm_Name, OHA.Firm_FY_End_Date DESC;