使用if,else in function

时间:2014-02-26 12:22:47

标签: sql-server tsql

我使用nelow查询,如果,但发生错误

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 

1 个答案:

答案 0 :(得分:1)

您需要使用CASE表达式

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