将CASE转换为IIF以获取Access查询

时间:2015-11-19 04:07:12

标签: sql-server ms-access access-vba case iif

我似乎无法找到如何将以下用T-SQL编写的查询转换为要在vba中使用的访问查询。我已经读过使用IIF而不是CASE(因为Access'SQL不支持这种情况),但尝试了许多不同的方法,无法让它工作。

sSQL = "SELECT ba.BusinessEntityID,ba.AddressID
          ,(CASE WHEN ba.BusinessEntityID > 5
            THEN
            (SELECT pp.FirstName FROM [Person].[Person] pp
            WHERE pp.BusinessEntityID = ba.BusinessEntityID)
           Else 'AA' END) AS 'TEST'
    FROM Person.BusinessEntityAddress ba
    INNER JOIN person.AddressType at ON at.AddressTypeID = ba.AddressTypeID
    WHERE ba.BusinessEntityID < 11;"`

尝试运行上面的查询时,我收到如下错误消息..

  

运行时错误3075查询中的语法错误(缺少运算符)   表达式'(例如ba.BusinessEntityID&gt; 5那么(选择   pp.FirstName FROM [Person]。[Person] pp WHERE pp.BusinessEntityID =   ba.BusinessEntityID)Else'AA'END)AS'TEST'

2 个答案:

答案 0 :(得分:0)

IIF语法:

IIF(condition, if_true_part, if_false_part)   

此外,如果MS Access中没有“AS”,则无法使用假名。

所以,请尝试下一步

sSQL = "SELECT ba.BusinessEntityID,ba.AddressID
          ,IIF(ba.BusinessEntityID > 5
            ,(SELECT pp.FirstName FROM Person pp
            WHERE pp.BusinessEntityID = ba.BusinessEntityID)
            ,'AA') AS 'TEST'
    FROM BusinessEntityAddress AS ba
    INNER JOIN AddressType AS at ON at.AddressTypeID = ba.AddressTypeID
    WHERE ba.BusinessEntityID < 11;"

还有其他两种方式:

1)创建一个VBA函数,它将返回“FirstName”;

2)加入(左或内,你需要的)表“人”

答案 1 :(得分:0)

使用Access时,请使用SWITCH功能:http://www.techonthenet.com/access/functions/advanced/switch.php

其他部分只是说条件成立。

sSQL = "SELECT ba.BusinessEntityID, ba.AddressID, 
         SWITCH(ba.BusinessEntityID > 5, 
        (SELECT pp.FirstName FROM [Person].[Person] 
        WHERE pp.BusinessEntityID = ba.BusinessEntityID), 
        TRUE, 'AA') AS 'TEST'
        FROM Person.BusinessEntityAddress ba
        INNER JOIN person.AddressType at ON at.AddressTypeID = ba.AddressTypeID
        WHERE ba.BusinessEntityID < 11"