如何在SQL中的一行上声明和分配变量


131

我想要类似的东西

DECLARE myVariable nvarchar[MAX] = "hello world".

如果您向我展示如何在字符串中编码引号,则可获得加分。

例如:

我想要读取字符串

John said to Emily "Hey there Emily"

我的尝试是

DECLARE myVariable nvarchar[MAX] = "John said to Emily \"Hey there Emily\""

4
SQL Server中的字符串定界符'不是"
奥德

Answers:


183

开始:

DECLARE @var nvarchar(max) = 'Man''s best friend';

您会注意到,'通过将其加倍到可以逃脱''

由于字符串定界符'不是",因此无需转义"

DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';

MSDN页面上的第二个示例DECLARE显示了正确的语法。


5
您还可以从select语句初始化,例如:声明@eid uniqueidentifier =(从t_Event中选择前1个id)
Damien Sawyer

13

在SQL 2008上这是有效的

DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable

在sql server 2005上,您需要执行此操作

DECLARE @myVariable nvarchar(Max) 
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable

3

您几乎已经明白了:

DECLARE @myVariable nvarchar(max) = 'hello world';

看到这里的文档

对于引号,SQL Server使用撇号而不是引号:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

如果需要在字符串中使用双撇号,请使用:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.