代码之家  ›  专栏  ›  技术社区  ›  Tony

T-SQL为什么我只能引用一次临时对象?

  •  0
  • Tony  · 技术社区  · 15 年前

    用tmp_行作为 ( 从[DBO]中选择*。[客户] )

    select * from tmp_rows;
    select count(*) from tmp_rows;
    

    我无法获取tmp_行的计数,因为我得到了错误: 对象名“tmp_rows”无效

    如果我评论“select*”查询,一切正常

    我需要选择所有行,然后获取它们的计数,如何做到这一点?

    4 回复  |  直到 15 年前
        1
  •  4
  •   codingbadger    15 年前
    with tmp_rows as 
    (
        select * from [dbo].[customer]
    )
    
    select * from tmp_rows;
    select @@rowcount;
    

    在使用中声明语句 with 您正在声明CTE-可以找到有关CTE的更多信息 here

        2
  •  4
  •   Guffa    15 年前

    使用创建的临时对象 with 关键字只能使用一次。如果要多次使用临时表,可以创建它:

    select *
    into #tmp_tows
    from dbo.customer
    
    select * from #tmp_rows
    
    select count(*) from #tmp_rows
    
    drop table #tmp_rows
    

    即使您想对结果执行两次不同的操作(例如,在结果之前获取计数),也可以这样做。

        3
  •  1
  •   devio    15 年前

    以分号结尾的CTE ; .

    但是在WITH语句中可以有1个以上的CTE:

    with tmp_rows as 
    (
        select * from [dbo].customer
    ),
    count_rows as
    (
        select COUNT(*) count_rows from tmp_rows
    )
    select * from count_rows, tmp_rows;
    
        4
  •  0
  •   Peter Radocchia    15 年前

    tmp_rows 是公共表表达式(CTE),CTE的作用域在语句级别:

    -- 1st statement, works fine.
    with tmp_rows as (select * from [dbo].[customer])
    select * from tmp_rows;
    
    -- 2nd statement, returns an error, since tmp_rows is out of scope.
    select count(*) from tmp_rows;
    

    到第二条语句执行时, 三棱柱 已经超出范围。

    请注意,CTE类似于局部作用域 意见 不是桌子。结果集从未实现。如果需要具体化结果集,请改用本地临时表或表变量。