Reputation: 413
On SQL 2000:
I am trying to write a dynamic UDF that will pull the values of one of five fields depending on the input criteria. Here is what I have so far:
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
I have used a single SELECT statement to return a value, and I have used the CASE WHEN THEN structure to return hard-coded values. Not having any luck blending the two. ** The names have been changed to protect the innocent. **
UPDATE: Got it to work as below. The parentheses made all the difference in the world.
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
Upvotes: 0
Views: 51
Reputation: 2845
Try this one, see if it answer your requirement.
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
Upvotes: 2