关键字'with'附近的语法不正确.

Kyl*_*ers 17 sql sql-server sql-server-2008

您好我想弄清楚为什么在MSSQL中将我的兼容模式从80切换到100会破坏我的功能?

    Microsoft SQL Server 2008 R2 (RTM) - 10.50.1617.0 (X64)   Apr 22 2011 19:23:43
Copyright (c) Microsoft Corporation  Express Edition with Advanced Services (64-bit) on
Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
Run Code Online (Sandbox Code Playgroud)

这是我的功能:

GO
ALTER FUNCTION [dbo].[GetRoot] 
(
    @Param1 int 
)
RETURNS varchar(50)
AS
BEGIN
DECLARE @ReturnValue varchar(50)
with results as
    (
        select parentouid,net_ouid from net_ou where net_ouid=@Param1
        union all
        select t2.parentouid,t2.net_ouid from net_ou t2 
        inner join results t1 on t1.parentouid = t2.net_ouid where t2.parentouid <> t1.net_ouid
    )   
    select @ReturnValue = net_ou.displayname 
    from  NET_OU RIGHT OUTER JOIN
    results ON net_ou.net_ouid = results.ParentouID where results.parentouid=results.net_ouid

    RETURN @ReturnValue

END
Run Code Online (Sandbox Code Playgroud)

Abe*_*ler 36

尝试在with前面扔一个半冒号:

;with results as
    (
        select parentouid,net_ouid from net_ou where net_ouid=@Param1
        union all
        select t2.parentouid,t2.net_ouid from net_ou t2 
        inner join results t1 on t1.parentouid = t2.net_ouid where t2.parentouid <> t1.net_ouid
    )   
Run Code Online (Sandbox Code Playgroud)

这篇文章读明白,为什么你需要做到这一点.Snipit:

但是,如果CTE不是批处理中的第一个语句,则必须在WITH关键字前面加上分号.作为一种最佳实践,我更喜欢在我的所有CTE前面加上分号 - 我发现这种一致的方法比记住我是否需要分号更容易.

就个人而言,我并不是为每一个 CTE 都这样做,但如果这样可以让事情变得更容易,那么它就不会有任何伤害.

  • 显然,30秒有什么不同!:) +1无论如何. (3认同)

JNK*_*JNK 5

之前添加分号WITH:

;with results as
    (
        select parentouid,net_ouid from net_ou where net_ouid=@Param1
        union all
        select t2.parentouid,t2.net_ouid from net_ou t2 
        inner join results t1 on t1.parentouid = t2.net_ouid where t2.parentouid <> t1.net_ouid
    )   
    select @ReturnValue = net_ou.displayname 
    from  NET_OU RIGHT OUTER JOIN
    results ON net_ou.net_ouid = results.ParentouID where results.parentouid=results.net_ouid

    RETURN @ReturnValue

END
Run Code Online (Sandbox Code Playgroud)

CTE声明需要是批处理中的第一个命令.