0

我需要一个函数,其中包含来自其他表的多个 WHERE 条件:

CREATE FUNCTION [dbo].[Table2](@Id INT) 
RETURNS money
AS 
BEGIN
 DECLARE @cost money
 SELECT @koszt = SUM(Value)
 FROM [dbo].[Cost]
  WHERE ([ID_CostCategory] --I need to add here one more condition [ID_Department]
  return @cost
END

请帮助如何获得它。

4

2 回答 2

0

如果我正确理解了您的评论,也许在您的函数中引入第二个参数就可以了:

CREATE FUNCTION [dbo].[Table2](@CategoryId INT, @DepartmentId INT) 
   RETURNS money
AS 
BEGIN
   DECLARE @cost money
   SELECT @cost = SUM(Value)
   FROM [dbo].[Cost]
   WHERE ([ID_CostCategory] = @CategoyId AND [ID_Department] = @DepartmentId)
   return @cost
END
于 2013-09-14T09:03:06.040 回答
0

首先,出于性能原因,我将使用内联 UDF 而不是标量函数。

其次,有两种选择:

1) 显示每个部门总数的功能

CREATE FUNCTION [dbo].[Table2](@pID_CostCategory INT) 
RETURNS TABLE
AS 
RETURN
    SELECT  [ID_Department], SUM(Value) AS koszt
    FROM    [dbo].[Cost]
    WHERE   [ID_CostCategory] = @pID_CostCategory
    GROUP BY[ID_Department];
GO  

或者

2) 一个有两个参数的函数,第二个参数是可选的

CREATE FUNCTION [dbo].[Table2](@pID_CostCategory INT, @pID_Department INT=NULL) 
RETURNS TABLE
AS 
RETURN
    SELECT  SUM(Value) AS koszt
    FROM    [dbo].[Cost]
    WHERE   [ID_CostCategory] = @pID_CostCategory
    AND     ([ID_Department] = @pID_Department OR @pID_Department IS NULL)
GO
于 2013-09-14T10:10:09.143 回答