SumIf 2012的SQL函数

时间:2015-05-14 23:24:54

标签: sql sql-server

我有以下sql函数,但没有正确运行,预期的返回值是总

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create FUNCTION [dbo].[SumIf](@ColumnName [varchar](100), @Criteria [varchar](500))
RETURNS [decimal] AS 
BEGIN
    -- Declare the return variable here
    DECLARE @Total Decimal
    DECLARE @TableName Decimal
    Select @Total = SUM(@ColumnName) from @TableName where  @Criteria
    RETURN @Total

END

使用语法类似于

选择dbo.sumif(fees.fee_amount,Fees.Fee_Code ='B01')

因此,表名也需要从传递的columnname变量中提取。

3 个答案:

答案 0 :(得分:0)

我认为你不能以这种方式实现你的功能。您实际上是在尝试将表达式传递给我认为在SQL Server中不可能的函数。您可能能够使用动态SQL传递字符串,但不能像您希望的那样干净利落。

答案 1 :(得分:0)

您需要动态SQL来执行此操作,但遗憾的是您无法在UDF中使用动态SQL。试试这个 -

DECLARE @ColumnName [nvarchar](100) = '' --fill in values here
DECLARE @TableName [nvarchar](100) = ''
DECLARE @Criteria [nvarchar](500) = ''

DECLARE @s nvarchar(max)
DECLARE @res bigint

set @s = 'SELECT @result = SUM(' + @ColumnName + ') from ' + @TableName + ' where ' + @Criteria
exec sp_executesql @s, N'@result OUTPUT', @result = @res OUTPUT
select @res

答案 2 :(得分:0)

你走错了路。如果您想将sumif()放在select语句中,则需要使用用户定义的聚合函数,而不仅仅是用户定义的函数。您已将@TableName声明为decimal然后在from子句中使用它的事实指向其他问题。

所以,我的建议是你只是在线执行此操作:

select sum(case when <condition> then <columnname> else 0 end) as sumval
from <tablename>

如果您想要一个编程块将数据放在一起,那么使用存储过程。类似的东西:

Create FUNCTION [dbo].SumIf(@ColumnName varchar(100),
                            @TableName varchar(255)
                            @Criteria varchar(500),
                            @Total Decimal OUTPUT)
                           ) AS 
BEGIN
    DECLARE @sql nvarchar(max) = 'Select @Total = SUM(@ColumnName) from @TableName where @Criteria';
    set @sql = replace(@sql, '@ColumnName', @ColumnName);
    set @sql = replace(@sql, '@TableName', @TableName);
    set @sql = replace(@sql, '@Criteria', @Criteria);
    sp_execute_sql @sql, N'@total decimal output', @total = @total output;
END;
相关问题