Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.
The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.
Initialization is an optional thing while declaring. By default, DECLARE initializes variable to NULL. Using the keyword 'AS' is optional. To declare more than one local variable, use a comma after the first local variable definition, and then define the next local variable name and data type.
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.
Here goes:
DECLARE @var nvarchar(max) = 'Man''s best friend';
You will note that the '
is escaped by doubling it to ''
.
Since the string delimiter is '
and not "
, there is no need to escape "
:
DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';
The second example in the MSDN page on DECLARE
shows the correct syntax.
on sql 2008 this is valid
DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable
on sql server 2005, you need to do this
DECLARE @myVariable nvarchar(Max)
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable
You've nearly got it:
DECLARE @myVariable nvarchar(max) = 'hello world';
See here for the docs
For the quotes, SQL Server uses apostrophes, not quotes:
DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';
Use double apostrophes if you need them in a string:
DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With