动态数据库名称的时候,使用sp_executesql

 

参考http://www.yjs001.cn/view/17945868128847470518.html

这个链接,根据自己的情况写出

 

set @SqlSJX='select @SJX = COUNT(*) from '+ @SqlName +' where Box not in (''CGX'',''YSC'',''LJX'') 
and isnull(Inside,0)=0 and MailDate<>'''' and CONVERT(date,RecDate,23) >= '+''''+ cast(@StartTime as nvarchar(30)) +''''

exec sp_executesql @SqlSJX,N'@SJX int output',@SJX output

 

对于https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql微软官方例子又是另一种方法

DECLARE @IntVariable int;  
DECLARE @SQLString nvarchar(500);  
DECLARE @ParmDefinition nvarchar(500);  
DECLARE @max_title varchar(30);  

SET @IntVariable = 197;  
SET @SQLString = N'SELECT @max_titleOUT = max(JobTitle)   
   FROM AdventureWorks2012.HumanResources.Employee  
   WHERE BusinessEntityID = @level';  
SET @ParmDefinition = N'@level tinyint, @max_titleOUT varchar(30) OUTPUT';  

EXECUTE sp_executesql @SQLString, @ParmDefinition, @level = @IntVariable, @max_titleOUT=@max_title OUTPUT;  
SELECT @max_title;  

 

posted @ 2017-07-18 17:56  王家小西  阅读(297)  评论(0编辑  收藏  举报