如何在 SQL 中的一行中声明和分配变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3525539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I declare and assign a variable on a single line in SQL
提问by Justin
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\""
回答by Oded
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 "
:
由于字符串分隔符 is'
和 not "
,因此无需转义"
:
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.
MSDN 页面上的第二个示例DECLARE
显示了正确的语法。
回答by SQLMenace
on sql 2008 this is valid
在 sql 2008 上这是有效的
DECLARE @myVariable nvarchar(Max) = 'John said to Emily "Hey there Emily"'
select @myVariable
on sql server 2005, you need to do this
在 sql server 2005 上,你需要这样做
DECLARE @myVariable nvarchar(Max)
select @myVariable = 'John said to Emily "Hey there Emily"'
select @myVariable
回答by Daniel Renshaw
You've nearly got it:
你几乎明白了:
DECLARE @myVariable nvarchar(max) = 'hello world';
See herefor the docs
有关文档,请参见此处
For the quotes, SQL Server uses apostrophes, not quotes:
对于引号,SQL Server 使用撇号,而不是引号:
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''';