Thursday, January 27, 2011

Is there a way to make a TSQL variable constant?

Is there a way to make a TSQL variable constant?

  • There are no such thing as "creating a constant" in database literature. Constants exist as they are and often called values. One can declare a variable and assign a value (constant) to it. From a scholastic view:

    DECLARE @two INT
    SET @two = 2
    

    Here @two is a variable and 2 is a value/constant.

  • No but you can create a function and hardcode it in there and use that

    Here is an example

    create function fnConstant()
    returns int
    as
    begin
    return 2
    end
    go
    
    select dbo.fnConstant()
    
    From SQLMenace
  • No, but good old naming conventions should be used.

    declare @MY_VALUE as int
    
    From jms
  • Okay, lets see

    Constants are immutable values which are known at compile time and do not change for the life of the program

    that means you can never have a constant in SQL Server

    declare @myvalue as int
    set @myvalue = 5
    set @myvalue = 10--oops we just changed it
    

    the value just changed

    From SQLMenace
  • @ Nick: those are mutable (by calling SET later on), not constant.

    There is no built-in support for constants in T-SQL. You could use SQLMenace's approach to simulate it (though you can never be sure whether someone else has overwritten the function to return something else…), or possibly write a table containing constants, as suggested over here. Perhaps write a trigger that rolls back any changes to the ConstantValue column?

0 comments:

Post a Comment