需要有关SQL UDF的帮助?

时间:2011-05-06 02:57:57

标签: sql-server-2005 sql-server-2000

在SQL 2000上:

我正在尝试编写一个动态UDF,它将根据输入条件提取五个字段之一的值。以下是我到目前为止的情况:

CREATE FUNCTION dbo.fBudgetBid ( @sJob int, @sCO nvarchar(10), @sCat nvarchar(10) )
RETURNS float
AS
BEGIN
  Declare @ERC float
  Set @ERC = Case @sCat
  WHEN 'Field' Then Select [Field] From [dbo].[Estimate] Where [Job] = @sJob AND [CO] = @sCO  
  WHEN 'Eng' Then Select [Eng] From [dbo].[Estimate] Where [Job] = @sJob AND [CO] = @sCO  
  WHEN 'PM' Then Select [PM] From [dbo].[Estimate] Where [Job] = @sJob AND [CO] = @sCO  
  WHEN 'Shop' Then Select [Shop] From [dbo].[Estimate] Where [Job] = @sJob AND [CO] = @sCO  
  WHEN 'Purch' Then Select [Purch] From [dbo].[Estimate] Where [Job] = @sJob AND [CO] = @sCO  
  END
  Return @ERC
END

我使用了一个SELECT语句来返回一个值,并且我使用了CASE WHEN THEN结构来返回硬编码值。没有运气混合两者。 **这些名字已被更改以保护无辜者。 **

更新:按照以下方式工作。括号在世界上造就了一切。

BEGIN
 Return (Case @sCat
  WHEN 'Field' Then (Select [Field] From [dbo].[Estimate] Where [Job] = @sJob AND [CO] = @sCO)
  WHEN 'Eng' Then (Select [Eng] From [dbo].[Estimate] Where [Job] = @sJob AND [CO] = @sCO)  
  WHEN 'PM' Then (Select [PM] From [dbo].[Estimate] Where [Job] = @sJob AND [CO] = @sCO)
  WHEN 'Shop' Then (Select [Shop] From [dbo].[Estimate] Where [Job] = @sJob AND [CO] = @sCO)  
  WHEN 'Purch' Then (Select [Purch] From [dbo].[Estimate] Where [Job] = @sJob AND [] ] = @sCO)
  END)
END

1 个答案:

答案 0 :(得分:2)

试试这个,看看它是否符合您的要求。

DEClARE @ERC FLOAT

SELECT @ERC = CASE @sCat WHEN 'Field' THEN [Field] 
             WHEN 'Eng' THEN [Eng] 
             WHEN 'PM' THEN [PM] 
             WHEN 'Shop' THEN [Shop] 
             WHEN 'Purch' THEN [Purch] END
FROM [dbo].[Estimate] 
WHERE [Job] = @sJob 
AND [CO] = @sCO  

RETURN @ERC