Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make a TSQL variable constant?

Is there a way to make a TSQL variable constant?

like image 554
TheEmirOfGroofunkistan Avatar asked Aug 25 '08 19:08

TheEmirOfGroofunkistan


People also ask

How do you declare a constant variable in SQL?

General Syntax to declare a constant is:constant_name CONSTANT datatype := VALUE; constant_name is the name of the constant i.e. similar to a variable name. The word CONSTANT is a reserved word and ensures that the value does not change. VALUE - It is a value which must be assigned to a constant when it is declared.

How do you keep a variable constant?

Say you want to keep cell A2 constant. To do that, click on the cell reference in the formula bar (A2), and enter $ before column and row ($A$2). You can also press F4 on the keyboard to make variable cell constant.

How do I change the value of a variable in SQL?

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.


2 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() 
like image 170
SQLMenace Avatar answered Sep 17 '22 18:09

SQLMenace


One solution, offered by Jared Ko is to use pseudo-constants.

As explained in SQL Server: Variables, Parameters or Literals? Or… Constants?:

Pseudo-Constants are not variables or parameters. Instead, they're simply views with one row, and enough columns to support your constants. With these simple rules, the SQL Engine completely ignores the value of the view but still builds an execution plan based on its value. The execution plan doesn't even show a join to the view!

Create like this:

CREATE SCHEMA ShipMethod GO -- Each view can only have one row. -- Create one column for each desired constant. -- Each column is restricted to a single value. CREATE VIEW ShipMethod.ShipMethodID AS SELECT CAST(1 AS INT) AS [XRQ - TRUCK GROUND]       ,CAST(2 AS INT) AS [ZY - EXPRESS]       ,CAST(3 AS INT) AS [OVERSEAS - DELUXE]       ,CAST(4 AS INT) AS [OVERNIGHT J-FAST]       ,CAST(5 AS INT) AS [CARGO TRANSPORT 5] 

Then use like this:

SELECT h.* FROM Sales.SalesOrderHeader h JOIN ShipMethod.ShipMethodID const     ON h.ShipMethodID = const.[OVERNIGHT J-FAST] 

Or like this:

SELECT h.* FROM Sales.SalesOrderHeader h WHERE h.ShipMethodID = (SELECT TOP 1 [OVERNIGHT J-FAST] FROM ShipMethod.ShipMethodID) 
like image 31
mbobka Avatar answered Sep 20 '22 18:09

mbobka