3

你能解释一下奇怪的行为吗?

DECLARE @t VARCHAR(256) = ''

SELECT @t = @t + CAST(smb.symbol AS VARCHAR(256))
FROM (
    SELECT 1,'7'
    UNION ALL
    SELECT 2,'8'
    UNION all
    SELECT 3,'9'
) AS smb(n, symbol)
ORDER BY n

SELECT @t

输出:

789

没关系对我来说。

DECLARE @t VARCHAR(256) = ''

SELECT @t = @t + CAST(smb.symbol AS VARCHAR(256))
FROM (
    SELECT NUMS.N-1 AS N, CHAR(N-1) AS symbol
    FROM (
        SELECT 1 + n.n1 + nn.n2 * 10 + nnn.n3 * 100 as N
        FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS n(n1)
            CROSS JOIN (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS nn(n2)
            CROSS JOIN (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS nnn(n3)
    ) AS NUMS
    WHERE NUMS.N BETWEEN 56 AND 58
) AS smb(N, symbol)
ORDER BY smb.N

SELECT @t

输出:

9

那么为什么第二个例子只输出最后一个符号呢?

4

1 回答 1

4

使用 mutlirows 变量赋值时不要依赖 order by。

试试这个,例如:

DECLARE @c INT = 0

SELECT
 @c = @c + x
FROM (VALUES(1),(2),(3)) AS src(x)
WHERE x BETWEEN 1 AND 3 
ORDER BY 1 - x DESC

SELECT @c

SET @c = 0

SELECT
 @c = @c + x
FROM (VALUES(1),(2),(3)) AS src(x)
WHERE x BETWEEN 1 AND 3 
ORDER BY x DESC

SELECT @c

http://sqlmag.com/sql-server/multi-row-variable-assignment-and-order

于 2013-05-13T12:12:29.037 回答