当前位置: 代码迷 >> Sql Server >> 一个关于动态表名调用的小疑点
  详细解决方案

一个关于动态表名调用的小疑点

热度:17   发布时间:2016-04-24 20:37:04.0
一个关于动态表名调用的小问题
 
DECLARE   @sql  nvarchar(max),
          @xxxxx int ,
          @Pdate varchar(100)
 
set @Pdate=1308
set @xxxxx=( select count(id) from  [1308]   )
 --这里正常

SET @sql = N' 
SET @xxxxx=(select count(id)   from '+QUOTENAME(@Pdate) +'  )
'
EXEC sp_executesql @sql 
 
PRINT @xxxxx


当表名为为动态时出错,后面需要调用@xxxxx  ,帮忙看下正确的语句是什么?

------解决方案--------------------
DECLARE   @sql  nvarchar(max),
          @xxxxx int ,
          @Pdate varchar(100)
set @Pdate=1308
set @xxxxx=( select count(id) from  [1308]   )
 --这里正常

SET @sql = N'SET @xxxxx=(select count(id)   from '+QUOTENAME(@Pdate) +')'
EXEC sp_executesql @sql ,N'@xxxxx int output',@xxxxx=@xxxxx output 
 
PRINT @xxxxx

------解决方案--------------------
DECLARE   @sql  nvarchar(max),
          @xxxxx int ,
          @Pdate varchar(100)
 
set @Pdate='1308'
set @xxxxx=( select count(id) from  [1308]   )
 --这里正常

SET @sql = N'DECLARE  @xxxxx int;
SET @xxxxx=(select count(id)   from '+QUOTENAME(@Pdate) +'  )
'
EXEC sp_executesql @sql 
 
PRINT @xxxxx
  相关解决方案