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

SqlSql Server-2008Variables

Sql Problem Overview


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

Sql Solutions


Solution 1 - Sql

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

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJustinView Question on Stackoverflow
Solution 1 - SqlOdedView Answer on Stackoverflow
Solution 2 - SqlSQLMenaceView Answer on Stackoverflow
Solution 3 - SqlDaniel RenshawView Answer on Stackoverflow