Sql server 在函数中使用if、else

Sql server 在函数中使用if、else,sql-server,tsql,Sql Server,Tsql,我使用nelow查询用于if,但出现错误 CREATE FUNCTION getStationCityCode ( @stationCode int ) RETURNS bigint AS BEGIN RETURN ( if((select cityCode from Station where code=@stationCode)!=0) select cityCode from Station where code=@statio

我使用nelow查询用于if,但出现错误

CREATE FUNCTION getStationCityCode
(
    @stationCode int
)
RETURNS bigint
AS BEGIN
    RETURN 
    (
          if((select cityCode from Station where code=@stationCode)!=0)
        select cityCode from Station where code=@stationCode
          else
             select 1 as cityCode
    )
END 

您需要使用
大小写
表达式

CREATE FUNCTION getStationCityCode
(
    @stationCode int
)
RETURNS bigint
AS BEGIN
    RETURN 
    (
        SELECT CASE WHEN cityCode!=0 THEN cityCode ELSE 1 END as cityCode
        FROM Station 
        WHERE code=@stationCode
    )
END