How do I declare and assign a variable on a single line in SQL
I want something like
DECLARE myVariable nvarchar[MAX] = "hello world".
Bonus points if you show me how to encode a quote in the string.
E.g.:
I want the string to read
John said to Emily "Hey there Emily"
my attempt would be
DECLARE myVariable nvarchar[MAX] = "John said to Emily \"Hey there Emily\""
Solution 1:
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.
Solution 2:
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
Solution 3:
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''';