January 1, 2010 at 11:58 am
Agreed... and thanks for the feedback.
--Jeff Moden
Change is inevitable... Change for the better is not.
January 1, 2010 at 12:52 pm
Jeff & Magoo,
Thanks a ton for the help and the suggestions. Will validate and then apply this code.
Regards
Naren
January 1, 2010 at 2:57 pm
Thanks for the feedback, Naren... especially about the validation part. I'd hate to see someone get into trouble because of something like rounding.
--Jeff Moden
Change is inevitable... Change for the better is not.
January 2, 2010 at 4:36 am
The reason why the code in your first sample will not give you the expected results is your ELSE condition:
since your ELSE condition is of data type DECIMAL, SQL Server will convert all results of your CASE statement to DECIMAL with the same scale value as the one you defined. For details, please see BOL, section "Data Type Precedence (Transact-SQL)". If you change the data type of @input to FLOAT it seems to give you the requested output. But it's still a numeric value. You can easily check that by trying to add a text to the result of the case statement.
You'd get your desired output (at least in terms of decimals displayed) when changing the ELSE condition to return a VARCHAR as well:
Using your sample data:
SELECT
CASE WHEN @decs = 2 THEN CAST(CAST(@input AS DECIMAL(17,2)) AS VARCHAR(19))
WHEN @decs = 1 THEN CAST(CAST(@input AS DECIMAL(17,1)) AS VARCHAR(19))
ELSE CAST(@input AS VARCHAR(19)) -- + 'test string'
END
This doesn't resolve the rounding issue at all. But that's not the point I'm trying to make (the issue is well covered already). My goal is to show you the reason why your original query didn't give you the desired output.
Viewing 4 posts - 16 through 18 (of 18 total)
You must be logged in to reply to this topic. Login to reply