I wrote a function that calculates the discount price of an item:
IF OBJECT_ID('fnDiscountPrice') IS NOT NULL DROP FUNCTION fnDiscountPrice; GO CREATE FUNCTION fnDiscountPrice (@ItemID int = 0) RETURNS money AS BEGIN DECLARE @DiscountPrice money SET @DiscountPrice = (SELECT (ItemPrice - DiscountAmount) FROM OrderItems WHERE ItemID = @ItemID); RETURN @DiscountPrice END
That operates as it should, although I am having difficulties using it properly within a query. I have tried it in two ways - both below. The take that the function is iterating through has 12 rows of data, therefore the query should return 12 results, however it returns 200+.
First attempt:
DECLARE @count int = 1; BEGIN WHILE (@count < (SELECT Count(ItemID) FROM OrderItems)) SELECT ItemID, ItemPrice, DiscountAmount, dbo.fnDiscountPrice(@count) AS DiscountPrice FROM OrderItems SET @count = @count + 1 END
Second attempt using a temporary table:
DECLARE @count int = 1; WHILE (@count < (SELECT Count(ItemID) FROM OrderItems)) BEGIN INSERT INTO #Temp SELECT ItemID, ItemPrice, DiscountAmount, dbo.fnDiscountPrice(@count) AS DiscountPrice FROM OrderItems WHERE ItemID = @count SET @count = @count + 1 END SELECT * FROM #Temp
As you can see they are very similiar, I just don't understand why I am getting the results I am.
Any insight you could provide would be both helpful and appreciated.