I am trying to write a stored procedure ( using SQL Server Management Studio 2008 R2) to retrieve the maximum measurement value from a table. This seemed like an easy thing to do, so I wrote a short stored procedure to get the MAX. However, when I ran the procedure, it returned a 0 rather than the expected 0.018 value.
When I hover my mouse over the MAX function, it displays “built-in function MAX(expression) RETURNS int”. So it seems to be casting my result as an int. This is rather annoying.
I guess I’ll have to calculate the maximum the long way unless anyone here has an easier solution. Any ideas?
ALTER PROCEDURE [dbo].[GetMaxOscillation] (@SerialNumber varchar (16), @Date datetime)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @MaxOsc DECIMAL(18,6)
SELECT @MaxOsc = MAX(Value)
FROM LoadListingOscillations
WHERE SerialNumber=@SerialNumber AND Date=@Date AND Value IS NOT NULL
RETURN @MaxOsc
SET NOCOUNT OFF
END
You have to do
MAX(CAST(Value AS DECIMAL(18,6)))I am guessing that the
Valueis not a DECIMAL, so you must cast it before the assignmentHere is the SQLFiddle to prove that if the table is set up as a Decimal then this will work
Here is a SQLFiddle that shows that the cast is needed
UPDATE
If
Valueis indeed a Decimal(18,6), then you need to make sure of your table values. Because, as you can see from my examples, this should workThe last thing that is probably more your problem is that you are returning an integer. I do not think you can return anything but an integer in SQL Server. You will have to do a
SELECT @MaxOscor use an OUTPUT variable