在sql查询中使用if,else in function

时间:2014-03-29 11:38:46

标签: sql-server tsql

我使用以下查询,但抛出错误:

CREATE FUNCTION getCustomerPaymentFunc (@customerCode bigint ) 
RETURNS bigint AS BEGIN
    RETURN 
    ( if(select coun from getCustomerPaymentCount (@customerCode))=0)
     select 0 as price      
      else          
        (select SUM(price) as code 
         from PaymentLog 
         where customerCode=@customerCode)
    ) END

我使用下面两个但是说:

函数中包含的select语句无法将数据返回给客户端

CREATE FUNCTION getCustomerPaymentFunc (@customerCode bigint ) 
RETURNS bigint AS BEGIN
RETURN 
(
  SELECT CASE WHEN (select coun from getCustomerPaymentCount(@customerCode))=0      
     THEN 0 ELSE 1 END as
 (select SUM(price) as code from PaymentLog 
  where customerCode=@customerCode)
     ) END

1 个答案:

答案 0 :(得分:2)

看起来您的意图是让函数返回给定PaymentLog的{​​{1}}表中的价格总和,或者如果customerCode不存在则返回0。如果这是正确的,你可以这样做:

customerCode

如果CREATE FUNCTION getCustomerPaymentFunc (@customerCode bigint) RETURNS bigint AS BEGIN DECLARE @result bigint SET @result= (SELECT ISNULL(SUM(price), 0) FROM PaymentLog WHERE customerCode = @customerCode) RETURN @result END 表中不存在customerCodePaymentLog函数将返回SUM(),您可以使用NULL或{ {1}}功能可将COALESCE值替换为ISNULL

请参阅MSDN:COALESCEISNULL