我不能调用sql函数

时间:2018-01-16 18:20:26

标签: sql sql-server

我写了这个函数

ALTER FUNCTION dbo.MEDIAVTRINEW
    (@CODIGO VARCHAR(25), 
     @YEAR VARCHAR(4),    
     @TRI INT)
RETURNS TABLE   
    RETURN  (SELECT ROUND(ISNULL(SUM(D2.D2_QUANT) / 3, 0), 2) AS MEDIA
    FROM SD2010 D2  
    WHERE D2.D_E_L_E_T_ = ''        
      AND D2.D2_TES IN ('502', '506', '505')
      AND D2.D2_COD = @CODIGO  
      AND ((@TRI = 1 
            AND D2.D2_EMISSAO >= CONCAT(@YEAR, '01', '01')
            AND D2.D2_EMISSAO <= CONCAT(@YEAR, '03', '31')
           )
           OR
           (@TRI = 2 
            AND D2.D2_EMISSAO >= CONCAT(@YEAR, '04', '01')
            AND D2.D2_EMISSAO <= CONCAT(@YEAR, '06', '31')
           )
           OR
           (@TRI = 3 
            AND D2.D2_EMISSAO >= CONCAT(@YEAR, '07', '01')
            AND D2.D2_EMISSAO <= CONCAT(@YEAR, '09', '31')
           )
           OR
           (@TRI = 4 
            AND D2.D2_EMISSAO >= CONCAT(@YEAR, '10', '01')
            AND D2.D2_EMISSAO <= CONCAT(@YEAR, '12', '31')
           )
          )
     )
GO

并试图调用下面的函数,但它没有显示在下拉列表中,我收到此错误:

  

无法找到colunm dbo或使用定义的函数或agreggate,或者名称不明确

当我尝试使用此功能时:

SELECT dbo.MEDIAVTRINEW('001004', '20171201', 4)

PS:我执行了单独的功能抛出参数并且工作正常。

2 个答案:

答案 0 :(得分:4)

您需要使用FROM子句来调用表值函数。您的语法适用于标量函数

Select * from dbo.MEDIAVTRINEW('001004','20171201',4)

答案 1 :(得分:1)

作为表值函数,我怀疑您需要 CROSS APPLY OUTER APPLY

示例

Select A.*
      ,B.*
 From  YourTable A
 Cross Apply dbo.MEDIAVTRINEW('001004','20171201',4) B

使用 OUTER APPLY 查看空值

将参数替换为字段值