How do I declare and assign a variable on a single line in SQL

Justin picture Justin · Aug 19, 2010 · Viewed 137.9k times · Source

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\""

Answer

Oded picture Oded · Aug 19, 2010

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.