- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我今天在 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
最佳答案
TLDR; 这不是用于跨行连接字符串的记录/支持的方法。它有时有效,但有时会失败,因为这取决于您获得的执行计划。
而是使用以下有保证的方法之一
SQL Server 2017+
SELECT @a = STRING_AGG([msg], '') WITHIN GROUP (ORDER BY [priority] ASC)
FROM bla
where autofix = 0
SQL Server 2005+
SELECT @a = (SELECT [msg] + ''
FROM bla
WHERE autofix = 0
ORDER BY [priority] ASC
FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)')
背景
KB article范德诺斯已经链接确实包括该行
The correct behavior for an aggregate concatenation query isundefined.
但随后提供了一种似乎确实表明确定性行为是可能的解决方法,从而使情况变得更加困惑。
In order to achieve the expected results from an aggregateconcatenation query, apply any Transact-SQL function or expression tothe columns in the SELECT list rather than in the ORDER BY clause.
有问题的查询不会将任何表达式应用于 ORDER BY
中的列条款。
2005年文章Ordering guarantees in SQL Server...是否说明
For backwards compatibility reasons, SQL Server provides support forassignments of type SELECT @p = @p + 1 ... ORDER BY at the top-mostscope.
在连接按预期工作的计划中,计算标量具有表达式 [Expr1003] = Scalar Operator([@x]+[Expr1004])
出现在排序上方。
在无法工作的计划中,计算标量出现在排序下方。如 this connect item 中所述从 2006 年开始,表达式 @x = @x + [msg]
出现在对每行进行评估的排序下方,但所有评估最终都使用预分配值 @x
。在 another similar Connect Item从 2006 年开始,微软的回应就提到“解决”这个问题。
Microsoft 对所有后续 Connect 项目中有关此问题(并且有很多)的回应都表明,这根本无法得到保证
we do not make any guarantees on the correctness of concatenationqueries (like using variable assignments with data retrieval in aspecific order). The query output can change in SQL Server 2008depending on the plan choice, data in the tables etc. You shouldn'trely on this working consistently even though the syntax allows you towrite a SELECT statement that mixes ordered rows retrieval withvariable assignment.
The behavior you are seeing is by design. Using assignment operations(concatenation in this example) in queries with ORDER BY clause hasundefined behavior. This can change from release to release or evenwithin a particular server version due to changes in the query plan.You cannot rely on this behavior even if there are workarounds. Seethe below KB article for more details:
http://support.microsoft.com/kb/287515 The ONLY guaranteedmechanism are the following:
- Use cursor to loop through the rows in specific order and concatenate the values
- Use for xml query with ORDER BY to generate the concatenated values
- Use CLR aggregate (this will not work with ORDER BY clause)
The behavior you are seeing is actually by design. This has to do withSQL being a set-manipulation language. All expressions in the SELECTlist (and this includes assignments too) are not guaranteed to beexecuted exactly once for each output row. In fact, SQL queryoptimizer tries hard to execute them as few times as possible. Thiswill give expected results when you are computing the value of thevariable based on some data in the tables, but when the value that youare assigning depends on the previous value of the same variable, theresults may be quite unexpected. If the query optimizer moves theexpression to a different place in the query tree, it may getevaluated less times (or just once, as in one of your examples). Thisis why we don't recommend using the "iteration" type assignments tocompute aggregate values. We find that XML-based workarounds ... usually work well for thecustomers
Even without ORDER BY, we do not guarantee that @var = @var + will produce the concatenated value for any statementthat affects multiple rows. The right-hand side of the expression canbe evaluated either once or multiple times during query execution andthe behavior as I said is plan dependent.
The variable assignment with SELECT statement is a proprietary syntax(T-SQL only) where the behavior is undefined or plan dependent ifmultiple rows are produced. If you need to do the string concatenationthen use a SQLCLR aggregate or FOR XML query based concatenation orother relational methods.
关于sql-server - nvarchar 连接/索引/nvarchar(max) 令人费解的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15138593/
将 nvarchar(max) 转换为 nvarchar(n) 并指示有更多数据的最快方法是什么? 例如:将列地址转换为 nvarchar(100),如果地址大于 100 个字符,则将最后 3 个字符
SO 和其他网站上都有多个帖子明确指出 nvarchar(max) 的最大长度是 2GB。但是,我在互联网和现实生活中也看到很多困惑,它实际上是 Unicode 中的 8000/4000。 我想知道什
我刚刚将表中的一个 nvarchar(MAX) 字段更改为 nvarchar(250)。有人可以告诉我如果条目超过 250 个字符,数据会发生什么情况吗? 我关心的不是可见数据,而是幕后发生的事情:
如果下面两个表的唯一区别是 nvarchar(50) 与 nvarchar(max) 以及每个表中的字符串,它们之间的一般存储和性能差异是什么字段范围从 1 到 50 个字符?这是在 SQL Serv
我在 SQL SERVER 2008 中有一个现有表,其中一列为 NVARCHAR(MAX) 并且其中只有少于 10 个字符的值。 此表正在生产中,其中包含数据。 我有一个要求,我必须将此列从 NVA
我正在构建一个表来跟踪数据库中特定对象的历史记录。目前我有以下列: HistoryId int IDENTITY(1,1) NOT NULL HistoryDate datetimeoffset(7)
在最终向用户呈现结果集之前,我对表变量进行了大量工作。例如,我可能会从许多不同的表中提取全部列,如下所示: DECLARE @tmp TABLE ( ID int, username nvarchar
我今天在 SQL Server(2008R2 和 2012)中遇到了一个非常奇怪的问题。我正在尝试结合使用连接和 select 语句来构建一个字符串。 我已经找到了解决方法,但我真的很想了解这里发生了
例如,nvarchar(max) 的性能是否低于 nvarchar(100)? 最佳答案 here (SO) 和 here (MSDN) 回答了同样的问题 引用 David Kreps 的回答: Wh
我们的 SQL Server(2005 和 2008)数据库中有几个表,其中的列定义为 nvarchar(4000)。我们有时需要能够存储比这更多的数据,并考虑改用 nvarchar(max)。现在回
当你在 fluent NHibernate 中设置一个字符串值时,它总是将 DB 值设置为 Nvarchar(255),我需要存储相当多的基于用户输入的长字符串,而 255 是不切实际的。 补充一下,
我在 sql 中有一个列,在某些情况下有时是 nvarchar 和数字。该列的数据类型为 nvarchar 。我只对我不需要它的数字的地方感兴趣。我使用如下案例 (SELECT case when i
在 SQL Server 中,如果您创建一个 NVARCHAR(MAX) 类型的列,并且仅在其中填充 128 个字符 - 与将其创建为 NVARCHAR 相比,它是否会消耗更多的存储空间(128) -
我们有一个索引列(ModelName),它在表中非常重要,并且与“目录号”非常相似,但它不是 PK。 大量按 ModelName 订购 ;正在使用 WHERE ModelName 等。 该列最初为 N
使用 SQL Server 2014,我有一个表,其中有 nvarchar(max)名为 [ASCII File] 的列它可以包含许多 K 的 ASCII 文本文件。然后我想对该文件执行 MD5 哈希
如何将 NTEXT 列转换为 NVARCHAR(MAX)? 我有 4 个数据库,其中有一个表存在于所有四个数据库中。在此表中,存在一个类型为 NTEXT except 的 Notes 列,该列为 nv
我面临的情况是必须使用脚本将现有数据库结构从 varchar 更新为 nvarchar。由于每次运行配置应用程序时都会运行此脚本,因此我宁愿确定列是否已更改为 nvarchar,而不是对表执行更改。我
我想知道定义 nvarchar(max) 类型的列而不是为其指定(较小的)最大大小是否有任何缺点。 我在某处读到,如果列值超过 4?KB,则剩余数据将添加到“溢出”区域,这是可以的。 我正在创建一个表
我想更改表 stk020 中的列类型。所以,我使用了这个查询.. ALTER TABLE [stk020] ALTER COLUMN [t16] nvarchar(Max) not null [t16
我正在尝试将存储在 CONTEXT_INFO 中的 nvarchar 转换回。 declare @LanguageCode nvarchar(6) = 'en'; declare @binvar va
我是一名优秀的程序员,十分优秀!