SQL中的IIF函数

时间:2016-05-14 20:04:09

标签: java database subquery hsqldb iif

我在MS Access中有以下SQL语句 -

WITH 
    qryAwayMatches AS (SELECT MATCHTEAM.FOOTBALLMATCHID, MATCHTEAM.TEAMID, MATCHTEAM.GAMETYPE, MATCHPROTOCOL.MATCHTEAMID, MATCHPROTOCOL.GOALNUMBER, 
    MATCHPROTOCOL.YELLOWCARDNUMBER, MATCHPROTOCOL.REDCARDNUMBER FROM MATCHTEAM LEFT JOIN MATCHPROTOCOL ON MATCHTEAM.ID = MATCHPROTOCOL.MATCHTEAMID WHERE (((MATCHTEAM.GAMETYPE)='Away'))),
    qryHomeMatches AS (SELECT MATCHTEAM.FOOTBALLMATCHID, MATCHTEAM.TEAMID, MATCHTEAM.GAMETYPE, MATCHPROTOCOL.MATCHTEAMID, MATCHPROTOCOL.GOALNUMBER, 
    MATCHPROTOCOL.YELLOWCARDNUMBER, MATCHPROTOCOL.REDCARDNUMBER FROM MATCHTEAM LEFT JOIN MATCHPROTOCOL ON MATCHTEAM.ID = MATCHPROTOCOL.MATCHTEAMID WHERE (((MATCHTEAM.GAMETYPE)='Home'))),
    qryMatchResult AS (SELECT qryHomeMatches.FootballMatchID, qryHomeMatches.TeamID AS HomeTeamID, 
    qryAwayMatches.TeamID AS AwayTeamID, 
    qryHomeMatches.GoalNumber>qryAwayMatches.GoalNumber AS HomeTeamWin, 
    qryHomeMatches.GoalNumber=qryAwayMatches.GoalNumber AS NoWin, 
    qryHomeMatches.GoalNumber<qryAwayMatches.GoalNumber AS AwayTeamWin 
    FROM qryHomeMatches INNER JOIN qryAwayMatches ON qryHomeMatches.FootballMatchID = qryAwayMatches.FootballMatchID)
    SELECT Round.RoundNumber, Team.Name, **IIf([HomeTeamWin],3,IIf([NoWin],1,0)) AS Points** 
    FROM Round 
    INNER JOIN (Team INNER JOIN (RoundDetail INNER JOIN qryMatchResult ON RoundDetail.FootballMatchID = qryMatchResult.FootballMatchID) ON Team.ID = qryMatchResult.HomeTeamID) ON Round.ID = RoundDetail.RoundID;

当我尝试使用HSQLDB在Java上按下按钮时执行此语句时,出现以下错误:

java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: IIF

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

从文档中可以看出,HSQLDB不支持IIF功能,我可以在函数列表中找到它:
http://hsqldb.org/doc/2.0/guide/builtinfunctions-chapt.html#bfc_general_functions

但好消息是:HSQLDB支持案例表达:
http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_query_expression

  

<强> CASE

     

案例规范

     

:: = |

     

:: = CASE ... [] END

     

:: = CASE ... []   END

     

:: =那么

     

:: =那么

     

:: = ELSE

     

:: = |

     

:: = [{} ...   ]

     

:: = | | | | | | | | | | | |

     

:: = | NULL

     

:: =

案例表达式由ANSII SQL标准定义,大多数数据库都支持它,而IIF函数是专有的和非标准的。

你可以改写:

iif ( condition, value_if_true, value_if_false )

以这种方式使用case表达式:

CASE WHEN condition THEN value_if_true ELSE value_if_false END

例如:

SELECT CASE WHEN col1>1 THEN 20 ELSE 50 END
FROM ....

而不是

SELECT iif(col1>1,20,50)
FROM ...