Using Declared Variables

  • Hello all,

    I am new to SQL coding. I would like to set my declared global variable like so. However when I do, it says that the column ratecode does not exist. This column is what I use in my "AS" statment. Is there a way to do this?

    Declare @ratecodeVar varchar(15)

    SELECT COALESCE(NULLIF(over_rate2,''), NULLIF(over_rate,''), std_rate) AS ratecode FROM dbo.matter WHERE clt_code = 'AME021' and mat_code = 'C133244'

    SET @ratecodeVar = ratecode

  • That's because you can't use a value from a SELECT, outside the SELECT. To assign the value is easier than you might have thought.

    Declare @ratecodeVar varchar(15)

    SELECT @ratecodeVar = COALESCE(NULLIF(over_rate2,''), NULLIF(over_rate,''), std_rate)

    FROM dbo.matter

    WHERE clt_code = 'AME021'

    AND mat_code = 'C133244'

    By the way, there's no such thing as global variables (user-defined at least) in SQL Server. All of them are local variables.

    Luis C.
    General Disclaimer:
    Are you seriously taking the advice and code from someone from the internet without testing it? Do you at least understand it? Or can it easily kill your server?

    How to post data/code on a forum to get the best help: Option 1 / Option 2
  • Thanks!

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply