Which variable assignment method would you use to specify a variables value in a script command

In this article, we will learn the notions and usage details of the SQL variable. In SQL Server, local variables are used to store data during the batch execution period. The local variables can be created for different data types and can also be assigned values. Additionally, variable assigned values can be changed during the execution period. The life cycle of the variable starts from the point where it is declared and has to end at the end of the batch. On the other hand, If a variable is being used in a stored procedure, the scope of the variable is limited to the current stored procedure. In the next sections, we will reinforce this theoretical information with various examples

Note: In this article examples, the sample AdventureWorks database is used.

SQL Variable declaration

The following syntax defines how to declare a variable:

DECLARE{@LOCAL_VARIABLEdata_type[=value]}

Now, let’s interpret the above syntax.

Firstly, if we want to use a variable in SQL Server, we have to declare it. The DECLARE statement is used to declare a variable in SQL Server. In the second step, we have to specify the name of the variable. Local variable names have to start with an at (@) sign because this rule is a syntax necessity. Finally, we defined the data type of the variable. The value argument which is indicated in the syntax is an optional parameter that helps to assign an initial value to a variable during the declaration. On the other hand, we can assign or replace the value of the variable on the next steps of the batch. If we don’t make any initial value assigned to a variable, it is initialized as NULL.

The following example will declare a variable whose name will be @VarValue and the data type will be varchar. At the same time, we will assign an initial value which is ‘Save Our Planet’:

DECLARE@TestVariableASVARCHAR(100)='Save Our Planet'

PRINT@TestVariable

Which variable assignment method would you use to specify a variables value in a script command

Assigning a value to SQL Variable

SQL Server offers two different methods to assign values into variables except for initial value assignment. The first option is to use the SET statement and the second one is to use the SELECT statement. In the following example, we will declare a variable and then assign a value with the help of the SET statement:

DECLARE@TestVariableASVARCHAR(100)

SET@TestVariable='One Planet One Life'

PRINT@TestVariable

Which variable assignment method would you use to specify a variables value in a script command

In the following example, we will use the SELECT statement in order to assign a value to a variable:

DECLARE@TestVariableASVARCHAR(100)

SELECT@TestVariable='Save the Nature'

PRINT@TestVariable

Which variable assignment method would you use to specify a variables value in a script command

Additionally, the SELECT statement can be used to assign a value to a variable from table, view or scalar-valued functions. Now, we will take a glance at this usage concept through the following example:

DECLARE@PurchaseNameASNVARCHAR(50)

SELECT@PurchaseName=[Name]

FROM [Purchasing].[Vendor]

WHEREBusinessEntityID=1492

PRINT@PurchaseName

Which variable assignment method would you use to specify a variables value in a script command

As can be seen, the @PurchaseName value has been assigned from the Vendor table.

Now, we will assign a value to variable from a scalar-valued function:

DECLARE@StockValASINT

SELECT@StockVal=dbo.ufnGetStock(1)

SELECT@StockValAS[VariableVal]

Which variable assignment method would you use to specify a variables value in a script command

Multiple SQL Variables

For different cases, we may need to declare more than one variable. In fact, we can do this by declaring each variable individually and assigned a value for every parameter:

DECLARE@Variable1ASVARCHAR(100)

DECLARE@Variable2ASUNIQUEIDENTIFIER

SET@Variable1='Save Water Save Life'

SET @Variable2='6D8446DE-68DA-4169-A2C5-4C0995C00CC1'

PRINT@Variable1

PRINT@Variable2

Which variable assignment method would you use to specify a variables value in a script command

This way is tedious and inconvenient. However, we have a more efficient way to declare multiple variables in one statement. We can use the DECLARE statement in the following form so that we can assign values to these variables in one SELECT statement:

DECLARE@Variable1 ASVARCHAR(100),@Variable2 ASUNIQUEIDENTIFIER

SELECT@Variable1='Save Water Save Life', @Variable2='6D8446DE-68DA-4169-A2C5-4C0995C00CC1'

PRINT@Variable1

PRINT@Variable2

Which variable assignment method would you use to specify a variables value in a script command

Also, we can use a SELECT statement in order to assign values from tables to multiple variables:

DECLARE@VarAccountNumberASNVARCHAR(15)

,@VariableNameASNVARCHAR(50)

SELECT@VarAccountNumber=AccountNumber ,@VariableName=Name

FROM[Purchasing].[Vendor]

WHEREBusinessEntityID=1492

PRINT@VarAccountNumber

PRINT @VariableName

Which variable assignment method would you use to specify a variables value in a script command

Useful tips about the SQL Variables

Tip 1: As we mentioned before, the local variable scope expires at the end of the batch. Now, we will analyze the following example of this issue:

DECLARE@TestVariable ASVARCHAR(100)

SET@TestVariable='Think Green'

GO

PRINT@TestVariable

Which variable assignment method would you use to specify a variables value in a script command

The above script generated an error because of the GO statement. GO statement determines the end of the batch in SQL Server thus @TestVariable lifecycle ends with GO statement line. The variable which is declared above the GO statement line can not be accessed under the GO statement. However, we can overcome this issue by carrying the variable value with the help of the temporary tables:

IFOBJECT_ID('tempdb..#TempTbl')ISNOTNULLDROPTABLE#TempTbl

DECLARE@TestVariableASVARCHAR(100)

SET @TestVariable='Hello World'

SELECT@TestVariableASVarValINTO#TempTbl

GO

DECLARE@TestVariableAS VARCHAR(100)

SELECT@TestVariable=VarValFROM#TempTbl

PRINT@TestVariable

Which variable assignment method would you use to specify a variables value in a script command

Tip 2: Assume that, we assigned a value from table to a variable and the result set of the SELECT statement returns more than one row. The main issue at this point will be which row value is assigned to the variable. In this circumstance, the assigned value to the variable will be the last row of the resultset. In the following example, the last row of the resultset will be assigned to the variable:

SELECTAccountNumber

FROM[Purchasing].[Vendor]

ORDERBYBusinessEntityID

DECLARE@VarAccountNumberAS NVARCHAR(15)

SELECT@VarAccountNumber=AccountNumber

FROM[Purchasing].[Vendor]

orderbyBusinessEntityID

SELECT @VarAccountNumberASVarValue

Which variable assignment method would you use to specify a variables value in a script command

Tip 3: If the variable declared data types and assigned value data types are not matched, SQL Server makes an implicit conversion in the value assignment process, if it is possible. The lower precedence data type is converted to the higher precedence data type by the SQL Server but this operation may lead to data loss. For the following example, we will assign a float value to the variable but this variable data type has declared as an integer:

DECLARE@FloatVarASFLOAT=12312.1232

DECLARE@IntVarASINT

SET@IntVar=@FloatVar

PRINT  @IntVar

Which variable assignment method would you use to specify a variables value in a script command

Conclusion

In this article, we have explored the concept of SQL variables from different perspectives, and we also learned how to define a variable and how to assign a value(s) to it.

  • Author
  • Recent Posts

Which variable assignment method would you use to specify a variables value in a script command

Esat Erkec is a SQL Server professional who began his career 8+ years ago as a Software Developer. He is a SQL Server Microsoft Certified Solutions Expert.

Most of his career has been focused on SQL Server Database Administration and Development. His current interests are in database administration and Business Intelligence. You can find him on LinkedIn.

View all posts by Esat Erkec

Which variable assignment method would you use to specify a variables value in a script command

What is the command to assign value to variables?

Use the ASSIGN Command. This command assigns an expression result or the field value to a variable. Variables are usually created with the DEFINE command and assigned a value.

How do you assign a command to a variable in shell script?

Bash Assign Output of Shell Command To And Store To a Variable.
var=$(command-name-here) var=$(command-name-here arg1) var=$(/path/to/command) var=$(/path/to/command arg1 arg2) ... .
var=`command-name-here` var=`command-name-here arg1` var=`/path/to/command` var=`/path/to/command arg1 arg2`.

How do you define a variable in a script?

To declare a variable, just type the name you want and set its value using the equals sign ( = ). As you can see, to print the variable's value, you should use the dollar sign ( $ ) before it. Note that there are no spaces between the variable name and the equals sign, or between the equals sign and the value.

How do I assign a value to a variable in PowerShell script?

To create a new variable, use an assignment statement to assign a value to the variable. You don't have to declare the variable before using it. The default value of all variables is $null . To get a list of all the variables in your PowerShell session, type Get-Variable .