Is there a way to make a TSQL variable constant?

Viewed 96246

Is there a way to make a TSQL variable constant?

12 Answers

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()

No, but good old naming conventions should be used.

declare @MY_VALUE as int

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?

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

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.

Related