现在有2个表
表A包含全部数据
表B有一个字段就是从表A中取得的不重复的部门名称数据
现在我想在存储过程里面建立表B里面包含的部门名称的表。我用的是游标,但是提示错误,请帮忙看一下。谢谢if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tmp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tmp]
declare @uname nvarchar(100)
select distinct 纳税人税务机关名称 into tmp from test1
declare cur1 cursor for 
select 纳税人税务机关名称 from tmpopen cur1
fetch next from cur1 into @uname
   while @@fetch_status=0
   begin
       select * into @uname from test1 where 纳税人税务机关名称=@uname       
       fetch next from cur1 into @uname
   end
close cur1
deallocate cur1服务器: 消息 170,级别 15,状态 1,过程 test,行 16
第 16 行: '@uname' 附近有语法错误。

解决方案 »

  1.   

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tmp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[tmp]
    declare @uname nvarchar(100)
    select distinct 纳税人税务机关名称 into tmp from test1
    declare cur1 cursor for 
    select 纳税人税务机关名称 from tmpopen cur1
    fetch next from cur1 into @uname
       while @@fetch_status=0
       begin
           --select * into @uname from test1 where 纳税人税务机关名称=@uname   
           exec ('select * into '+@uname+' from test1 where 纳税人税务机关名称='''+@uname+'''' )    
           fetch next from cur1 into @uname
       end
    close cur1
    deallocate cur1
      

  2.   

    select * into @uname from test1 where 纳税人税务机关名称=@uname
    这里应该是个表变量吧?
      

  3.   

    谢谢 执行的时候报错。服务器: 消息 170,级别 15,状态 1,行 1
    第 1 行: ' ' 附近有语法错误。
    服务器: 消息 170,级别 15,状态 1,行 1
    第 1 行: ' ' 附近有语法错误。
    服务器: 消息 170,级别 15,状态 1,行 1
    第 1 行: ' ' 附近有语法错误。
    服务器: 消息 170,级别 15,状态 1,行 1
    第 1 行: ' ' 附近有语法错误。
    存储过程: pubs.dbo.test
    返回代码 = 0
      

  4.   


    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tmp]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
    drop table [dbo].[tmp]
    declare @uname nvarchar(100)
    select distinct 纳税人税务机关名称 into tmp from test1
    declare @表变量名 table
    (字段...)declare cur1 cursor for 
    select 纳税人税务机关名称 from tmpopen cur1
    fetch next from cur1 into @uname
       while @@fetch_status=0
       begin
           insert into 表变量名
           select * from test1 where 纳税人税务机关名称=@uname       
           fetch next from cur1 into @uname
       end
    close cur1
    deallocate cur1
      

  5.   

    ...
          exec('select * into [' +@uname+'] from test1 where 纳税人税务机关名称='''+@uname+'''')
          fetch next from cur1 into @uname
    ...
      

  6.   

       begin
           insert into 表变量名
           select * from test1 where 纳税人税务机关名称=@uname       
           fetch next from cur1 into @uname
       end
    要是这么做的话 select * from test1 where 纳税人税务机关名称=@uname就没什么意义了吧?