错误提示:必须声明变量 '@tbstr'
目的:通过传递参数选择不同表,再进行处理
CREATE PROCEDURE test
@tbstr varchar(30)=''
 AS
DECLARE test_cursor CURSOR FOR 
select * from @tbstr
open test_cursor
--'''''
CLOSE test_cursor
DEALLOCATE test_cursor
GO

解决方案 »

  1.   

    应该这样写
    CREATE PROCEDURE test1
    @tbstr varchar(30)=''
     AS
    declare @vartable varchar(100) 
    set @vartable ='DECLARE test_cursor CURSOR FOR 
    select * from '+ @tbstr +'
    open test_cursorCLOSE test_cursor
    DEALLOCATE test_cursor'execute(@vartable)
    GO
      

  2.   

    http://community.csdn.net/Expert/topic/3322/3322036.xml?temp=.4478418
    http://community.csdn.net/Expert/topic/3219/3219498.xml?temp=.6246607用一個變量來代替declare @tab varchar(100)
    declare @sql varchar(1000)set @sql='select * from '+@tab
    exec @sql
      

  3.   

    改成这个:
    exec(' DECLARE test_cursor CURSOR FOR select * from  '+@tbstr+'')
      

  4.   

    用NorthWind测试:DECLARE @tbstr varchar(30)
    DECLARE @CompanyName varchar(40)
    set @tbstr='Customers'exec(' DECLARE test_cursor CURSOR FOR select CompanyName from  '+@tbstr+'')
    open test_cursorFETCH NEXT FROM test_cursor   INTO @CompanyName 
    WHILE @@FETCH_STATUS = 0
    BEGIN
       PRINT  @CompanyName  
       FETCH NEXT FROM test_cursor  INTO @CompanyName 
    ENDCLOSE test_cursor
    DEALLOCATE test_cursor
      

  5.   

    DECLARE @tbstr varchar(30)set @tbstr='Customers'exec(' DECLARE test_cursor CURSOR FOR select * from  '+@tbstr+'')
    open test_cursor
    CLOSE test_cursor
    DEALLOCATE test_cursor