create table test(a int,b int,c int)
insert into test select 1,1,1
insert into test select 2,2,2declare @a tinyint,@b tinyint,@c tinyint
set @a=1
set @b=1
set @c=1
declare @tname varchar(100)
declare @s varchar(8000)
set @tname='test'
set @s='declare the_same_cursor cursor
      for select *
      from '+@tname+'
      where '+@tname+'.a='+rtrim(@a)+' and '+@tname+'.b='+rtrim(@b)+' and '+@tname+'.c='+rtrim(@c)+'
      order by a'
exec(@s)open the_same_cursor set @a=null
set @b=null
set @c=nullfetch next from the_same_cursor into @a,@b,@cprint @a
print @b
print @cclose the_same_cursor
deallocate the_same_cursordrop table test

解决方案 »

  1.   

    create table test(a int,b int,c int)
    insert into test select 1,1,1
    insert into test select 2,2,2declare @a tinyint,@b tinyint,@c tinyint
    set @a=1
    set @b=1
    set @c=1
    declare @tname varchar(100)
    declare @s varchar(8000)
    set @tname='test'
    set @s='declare the_same_cursor cursor
          for select *
          from '+@tname+'
          where '+@tname+'.a='+rtrim(@a)+' and '+@tname+'.b='+rtrim(@b)+' and '+@tname+'.c='+rtrim(@c)+'
          order by a'
    exec(@s)open the_same_cursor set @a=null
    set @b=null
    set @c=nullfetch next from the_same_cursor into @a,@b,@cprint @a
    print @b
    print @cclose the_same_cursor
    deallocate the_same_cursordrop table test
      

  2.   

    怎么又发了两遍?楼上是一个例子,用于说明声明游标的操作可以放在动态SQL中交由EXEC语句执行,而外部可以调用这个EXEC()语句执行过程中声明的游标。