165

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\""
1
  • 6
    The string delimiter in SQL Server is ', not ".
    – Oded
    Commented Aug 19, 2010 at 19:39

3 Answers 3

238

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.

1
  • 12
    You can also initialize from a select statement, eg: declare @eid uniqueidentifier = (select top 1 id from t_Event) Commented Sep 8, 2016 at 20:32
18

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
0
7

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''';
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.