declare @tmp (id int)insert into @tmp select * from a where....insert into @tmp select * from @tmp where 条件1insert into @tmp select * from @tmp where 条件2....我想这样多次使用一个表变量,但上面的代码有一人问题,@tmp在每次插入时需要清空,这里想要一种类似中间变量的效果,应该怎么写??

解决方案 »

  1.   

    declare   @tmp   table(id   int) insert   into   @tmp   select   1 union  select 2insert   into   @tmp   select   *   from   @tmp  -- where   条件1 insert   into   @tmp   select   *   from   @tmp  -- where   条件2
    select * from @tmp/*id          
    ----------- 
    1
    2
    1
    2
    1
    2
    1
    2(所影响的行数为 8 行)
    */
      

  2.   

    直接用
    delete from @tmp
    清空,有什么问题吗?
      

  3.   

    declare   @tmp   table(id   int) insert   into   @tmp   select   1 union  select 2
    select * from @tmp
    insert   into   @tmp   select   *   from   @tmp   where id = 2
    select * from @tmp
    insert   into   @tmp   select   *   from   @tmp   where  id <=2
    select * from @tmp/*(所影响的行数为 2 行)id          
    ----------- 
    1
    2(所影响的行数为 2 行)
    (所影响的行数为 1 行)id          
    ----------- 
    1
    2
    2(所影响的行数为 3 行)
    (所影响的行数为 3 行)id          
    ----------- 
    1
    2
    2
    1
    2
    2(所影响的行数为 6 行)
    */
      

  4.   

    declare   @tmp   table(id   int) insert   into   @tmp   select  1 union all select 2delete @tmpinsert   into   @tmp   select  3 union all select 4select * from @tmp/*
    id
    -----------
    3
    4(2 row(s) affected)
    */
      

  5.   


    declare   @tmp   table(id   int) 
    insert   into   @tmp   select  1 union all select 2delete @tmpinsert   into   @tmp   select  3 union all select 4
    select * from @tmp
      

  6.   

    如果用临时表:
    create table #t(id   int) insert   into   #t   select  1 union all select 2truncate table #tinsert   into   #t   select  3 union all select 4select * from #t/*
    id
    -----------
    3
    4(2 row(s) affected)
    */
      

  7.   

    类似中间变量的效果
    什么意思??? 
    -------------------------
    insert   into   @tmp   select   *   from   @tmp   where id = 2从@tmp 查询记录,结果存入@tmp(不是插入)这里的条件1条件2只是略语,我想跟据存储过程的参数,进行动态查询if @参数1...
    insert   into   @tmp   select   *   from   @tmp   where   条件1 
    endif @参数2...
    insert   into   @tmp   select   *   from   @tmp   where   条件2 
    end是一个筛选的过程