2

I have a very basic question about declaring some variables in TSQL.

When i declare a numeric variable in TSQL like this, everthing is ok:

DECLARE @Value AS NUMERIC(18,2) = 1.23  

But what if i want the decimals to be set with a parameter?

DECLARE @NrOfDecimals AS INTEGER = 2
DECLARE @Value AS NUMERIC(18,@NrOfDecimals) = 1.23  
--This second line throws a compile error "Expecting  INTEGER"

So the second line throws a compile error "Expecting INTEGER".

But isn't @NrOfDecimals an Integer? So why is the compiler complaining??

Am i missing something??

6
  • The compiler is complaining because it wants a number, not a variable. A lot of T-SQL has restrictions like this. Why do you want to vary the number of decimals? Do you do this in any other language? Jun 19, 2013 at 7:41
  • Are you trying to round values in SQL? or why would you want to change the number of decimals like that?
    – JanR
    Jun 19, 2013 at 7:42
  • 2
  • @Damien_The_Unbeliever , i want to do this because we have a table with a field of type VARCHAR, but in some cases, the value in this field is actualy a numeric (could be 5 or 3.1 of 34.87). I want to do some math with this varchar/numeric value, so need to convert it to a numeric with the right nr of decimals
    – Jeroen1984
    Jun 19, 2013 at 7:49
  • 2
    I would declare @Value with the highest amount of decimals available. Handling data is one issue, displaying data with a varying amount of decimals should not be handled here.
    – Alexander
    Jun 19, 2013 at 8:46

1 Answer 1

2

You could dynamically create your queries and execute them.

This will work for the situation in your question:

DECLARE @NrOfDecimals AS INTEGER = 2
DECLARE @myCommand as NVARCHAR(1000)
SET @myCommand = 'DECLARE @value as numeric(18,' + CAST(@NrOfDecimals as VARCHAR) + ') = 1.23'
execute sp_executesql @myCommand

In order to do this for every situation, you should create a table with all queries you will have to run.

In order to create all of these queries you will have to use a cursor.

Documentation for cursors you can find here:

Also, I have answered another question and gave an example with a cursor:

1
  • 2
    Declaring a variable inside a separated dynamic statement (with its own scope of course) is useless.
    – Serge
    Jun 19, 2013 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.