SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GOCREATE PROC GetLastDealingDate   
AS  IF ( EXISTS ( SELECT * FROM tempdb.dbo.sysobjects WHERE name = '##a' ))
    DROP TABLE ##aDECLARE @sTableName varchar(15)   select top 1 name 
     into ##a
     from sysobjects 
    where substring(name, 1, 7) = 'xxxxxxx'
 order by name desc  select @sTableName = name from ##a  select * from @sTableNameGO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

解决方案 »

  1.   

    报错: Must declare the variable '@sTableName'。不知错在哪里? 
      

  2.   


    --表名为变量时,要使用动态SQL
    CREATE PROC GetLastDealingDate   
    AS  IF ( EXISTS ( SELECT * FROM tempdb.dbo.sysobjects WHERE name = '##a' ))
        DROP TABLE ##aDECLARE @sTableName varchar(15)   select top 1 name 
         into ##a
         from sysobjects 
        where substring(name, 1, 7) = 'xxxxxxx'
     order by name desc  select @sTableName = name from ##a  exec('select * from '+@sTableName)GO
      

  3.   

    DECLARE @sTableName varchar(15)
    这是定义一个字段符,怎么能在select * from @sTableName 这里当表用呢?
      

  4.   

    select * from @sTableName
    改为
    select @stablename
      

  5.   

    CREATE PROC GetLastDealingDate   
    AS 
    begin
    DECLARE @sTableName varchar(15)
    select @sTableName=name from sysobjects 
    where type='u' and substring(name,1,7)='tb' 
    order by name desc
    exec('select * from '+@sTableName)
    endexec GetLastDealingDate1 5
    5 6
    4 7不用临时表,用了你什么时候删除?
      

  6.   

    exec('select * from '+@sTableName)
      

  7.   

    exec('select * from '+@sTableName)
      

  8.   

    SET QUOTED_IDENTIFIER ON 
    GO
    SET ANSI_NULLS ON 
    GO
    CREATE PROC GetLastDealingDate   
    AS
      IF ( EXISTS ( SELECT * FROM tempdb.dbo.sysobjects WHERE name = '##a' ))
        DROP TABLE ##a
      DECLARE @sTableName varchar(15)
      select top 1 name into ##a
      from sysobjects 
      where substring(name, 1, 7) = 'xxxxxxx'
      order by name desc
      select @sTableName = name from ##a
      declare @sql varchar(8000)
      set @sql ='select * from '+ @sTableName
      exec(@sql)try
      

  9.   

    SET QUOTED_IDENTIFIER ON 
    GO
    SET ANSI_NULLS ON 
    GO
    CREATE PROC GetLastDealingDate   
    AS
      IF ( EXISTS ( SELECT * FROM tempdb.dbo.sysobjects WHERE name = '##a' ))
        DROP TABLE ##a
      DECLARE @sTableName varchar(15)
      select top 1 name into ##a
      from sysobjects 
      where substring(name, 1, 7) = 'xxxxxxx'
      order by name desc
      select @sTableName = name from ##a
      declare @sql varchar(8000)
      set @sql ='select * from '+ @sTableName
      exec(@sql)try~