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

Jus*_*tin 122 sql variables sql-server-2008

我想要类似的东西

DECLARE myVariable nvarchar[MAX] = "hello world".
Run Code Online (Sandbox Code Playgroud)

如果您告诉我如何在字符串中编码引号,则可以获得奖励积分.

例如:

我想要读取字符串

John said to Emily "Hey there Emily"
Run Code Online (Sandbox Code Playgroud)

我的尝试是

DECLARE myVariable nvarchar[MAX] = "John said to Emily \"Hey there Emily\""
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 170

开始:

DECLARE @var nvarchar(max) = 'Man''s best friend';
Run Code Online (Sandbox Code Playgroud)

你会注意到它'是通过加倍来逃脱的''.

由于字符串分隔符是'和否",因此无需转义":

DECLARE @var nvarchar(max) = '"My Name is Luca" is a great song';
Run Code Online (Sandbox Code Playgroud)

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

  • 您还可以从select语句初始化,例如:声明@eid uniqueidentifier =(从t_Event中选择前1个ID) (4认同)

SQL*_*ace 11

在sql 2008上这是有效的

DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable
Run Code Online (Sandbox Code Playgroud)

在sql server 2005上,你需要这样做

DECLARE @myVariable nvarchar(Max) 
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable
Run Code Online (Sandbox Code Playgroud)


Dan*_*haw 5

你几乎明白了:

DECLARE @myVariable nvarchar(max) = 'hello world';
Run Code Online (Sandbox Code Playgroud)

有关文档,请参见此处

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

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';
Run Code Online (Sandbox Code Playgroud)

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

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';
Run Code Online (Sandbox Code Playgroud)