数据库名 555
表明 studentsql语句为::  select @count=count(1) from [555].[dbo].[student]   这样写 执行通过 如果这样写 declare @demotable int
set @demotable=555select @count=count(1) from [@demotable].[dbo].[student]   
执行不通过 错误提示是 @demotable找不到
难道就不能动态指定表名吗??求高手指点

解决方案 »

  1.   


    --需动态sql,不可直接执行的
    declare @demotable int,@count int,@sql nvarchar(1000)
    set @demotable=555
    set @sql=N'select @count=count(1) from ['+convert(nvarchar(20),@demotable)+N'].[dbo].[student]'
    exec sp_executesql @sql,N'@count int output',@count out
    select @count 
      

  2.   

    如果数据库或表名用变量表示,则在执行查询的时候需要用动态SQL来实现,如#1楼所给的例子。