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

时间:2010-08-19 19:33:27

标签: sql sql-server-2008 variables

我想要像

这样的东西
DECLARE myVariable nvarchar[MAX] = "hello world".

如果您向我展示如何对字符串中的引号进行编码,则获得积分。

E.g:

我想要读取字符串

John said to Emily "Hey there Emily"

我的尝试将是

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

3 个答案:

答案 0 :(得分:155)

这里是:

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

您会注意到,'通过加倍''来转义。

由于字符串分隔符为'而非",因此无需转义"

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

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

答案 1 :(得分:9)

在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

答案 2 :(得分:3)

你差不多了:

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

请参阅here了解文档

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

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

如果您需要使用双撇号,请使用双撇号:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';
相关问题