How do I make the equivalent of "#define SomeValue 5" in sql transaction?

I need to make a long transact sql script where I have to use the same value many times and I don't want to write the literal value every time, but use what would be a preprocessor macro in C.

The point is that I will be using this script many times, with different values ​​for "SomeValue" and I only want to have a literal value in one place in the script, at the top where I see it and change it as needed, and then again run your script.

+3


source to share


2 answers


While you cannot define a constant in SQL, you can make a variable:

DECLARE @SomeValue INT = 5

SELECT *
FROM MyTable
WHERE ID = @SomeValue

SELECT *
FROM AnotherTable
WHERE SomeColumn = @SomeValue + 5

      

There are restrictions on where you can use variables. For example, you cannot use them in DDL . If you do this, you will receive an error:



DECLARE @SomeValue INT = 5
CREATE TABLE TestTable(IntColumn INT DEFAULT(@SomeValue))

      

This error is thrown:

Variables are not allowed in the CREATE TABLE statement.

+2


source


Have you tried declaring a default value at the very beginning of the script, for example: DECLARE @SomeValue int = 5



+1


source







All Articles