views:

2385

answers:

5

Is there a way to make a TSQL variable constant?

A: 

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.

Greg Hurlman
+3  A: 

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()
SQLMenace
+3  A: 

No, but good old naming conventions should be used.

declare @MY_VALUE as int
jms
A: 

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

SQLMenace
+1  A: 

@ 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?

Sören Kuklau