VARCHAR(MAX)在连接字符串时表现得很奇怪

时间:2011-01-24 09:40:50

标签: sql sql-server-2005 tsql

我有一个连接查询:

DECLARE @path NVARCHAR(max) 
SELECT @path = ISNULL(@path + '/', '') + url_segment 
    FROM navigation_self_and_parents(2813) ORDER BY depth ASC
SELECT @path

navigation_self_and_parents(2813)返回

id    par_id  title        url_segment    sequence        depth
2813  2816    testing1234  testing1234    0               0   
2816  2809    U            /fixedurl      0               -1   
2809  NULL    E            E              0               -2   

我的串联查询返回

'testing1234'             when using `NVARCHAR(MAX)` and
'E//fixedurl/testing1234' when using `NVARCHAR(4000)`

我最好的猜测是,使用NVARCHAR(MAX)会导致@path在每次设置时重新输入,从而在重新输入之前丢失设置的内容,或者在第一次设置时输入,然后后续连接调用静默失败。

我很想真正理解这种行为的根本原因。

更新

navigation_self_and_parents:

USE [SomeDatabase]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[navigation_self_and_parents]
(   
    @id int
)
RETURNS TABLE 
AS
RETURN 
(
    WITH navigation_self_and_parents (id, parent_id, title, url_segment, sequence_number, depth)
    AS
    (
        SELECT id, parent_id, title, url_segment, sequence_number, 0 FROM navigation_node WHERE id=@id 
        UNION ALL

        SELECT n.id, n.parent_id, n.title, n.url_segment, n.sequence_number, depth - 1 From navigation_node as n
        INNER JOIN navigation_self_and_parents as rn
        ON n.id = rn.parent_id
    )
    SELECT * FROM navigation_self_and_parents
)

navigation_node DDL:

CREATE TABLE [dbo].[navigation_node](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [title] [nvarchar](128) NULL,
    [url_segment] [nvarchar](max) NULL,
    [hidden] [bit] NOT NULL,
    [page_id] [int] NULL,
    [parent_id] [int] NULL,
    [sequence_number] [int] NOT NULL,
    [createdOn] [datetime] NOT NULL,
    [updatedOn] [datetime] NULL,
    [navigation_type_id] [int] NULL,
    ...snap

1 个答案:

答案 0 :(得分:4)

这种字符串连接方法通常可以正常工作,但不能保证。

the KB article for a similar issue中的官方行是“未定义聚合连接查询的正确行为。”

计划之间必须有一些微妙的区别。您可以调整查询以消除差异并获得所需的执行计划,或者您当然可以/应该使用XML PATH,就像使用SQL Server 2005一样,这可以记录下来。