【发布时间】:2013-02-14 19:47:12
【问题描述】:
我今天在 SQL Server(2008R2 和 2012)中遇到了一个非常奇怪的问题。我正在尝试使用串联和select 语句来构建一个字符串。
我找到了解决方法,但我真的很想了解这里发生了什么以及为什么它没有给我预期的结果。谁能给我解释一下?
http://sqlfiddle.com/#!6/7438a/1
根据要求,这里还有代码:
-- base table
create table bla (
[id] int identity(1,1) primary key,
[priority] int,
[msg] nvarchar(max),
[autofix] bit
)
-- table without primary key on id column
create table bla2 (
[id] int identity(1,1),
[priority] int,
[msg] nvarchar(max),
[autofix] bit
)
-- table with nvarchar(1000) instead of max
create table bla3 (
[id] int identity(1,1) primary key,
[priority] int,
[msg] nvarchar(1000),
[autofix] bit
)
-- fill the three tables with the same values
insert into bla ([priority], [msg], [autofix])
values (1, 'A', 0),
(2, 'B', 0)
insert into bla2 ([priority], [msg], [autofix])
values (1, 'A', 0),
(2, 'B', 0)
insert into bla3 ([priority], [msg], [autofix])
values (1, 'A', 0),
(2, 'B', 0)
;
declare @a nvarchar(max) = ''
declare @b nvarchar(max) = ''
declare @c nvarchar(max) = ''
declare @d nvarchar(max) = ''
declare @e nvarchar(max) = ''
declare @f nvarchar(max) = ''
-- I expect this to work and generate 'AB', but it doesn't
select @a = @a + [msg]
from bla
where autofix = 0
order by [priority] asc
-- this DOES work: convert nvarchar(4000)
select @b = @b + convert(nvarchar(4000),[msg])
from bla
where autofix = 0
order by [priority] asc
-- this DOES work: without WHERE clause
select @c = @c + [msg]
from bla
--where autofix = 0
order by [priority] asc
-- this DOES work: without the order by
select @d = @d + [msg]
from bla
where autofix = 0
--order by [priority] asc
-- this DOES work: from bla2, so without the primary key on id
select @e = @e + [msg]
from bla2
where autofix = 0
order by [priority] asc
-- this DOES work: from bla3, so with msg nvarchar(1000) instead of nvarchar(max)
select @f = @f + [msg]
from bla3
where autofix = 0
order by [priority] asc
select @a as a, @b as b, @c as c, @d as d, @e as e, @f as f
【问题讨论】:
-
这很好,但是您能否在问题中包含一些重现问题所需的代码? SQLFiddle 非常有用,但代码不应该存在 only 那里。
-
你到底是什么意思?这是 SQL 中的问题,而不是其他地方.. 对吗?
-
我的意思是你在 SQLfiddle 上的复制品,但它在问题的代码块中。
-
啊。当然。将其添加到问题中。 :)
标签: sql-server sql-server-2012 string-concatenation nvarchar