日期:2014-05-19  浏览次数:20624 次

SELECT @lMaxIndex = Max(lCompanyLogID) from ADCenter1.20070319.dbo.tCompanyLog
declare   @LinkServerName   nvarchar(100)   --数据库名
select   @LinkServerName     =   sDBName   from   ADCenter1.NDSPrimaryNew.dbo.tServerList   where   sServerType= '1 '
--取得数据库名称   如:2007019


SELECT   @lMaxIndex   =   Max(lCompanyLogID)   from   ADCenter1.20070316.dbo.tCompanyLog
print   @lMaxIndex

问题:我如何将上句中   20070316   变成我第一句中   @LinkServerName   的变量值


------解决方案--------------------
declare @LinkServerName nvarchar(100),@lMaxIndex varchar(20)
declare @sql nvarchar(1000)

select @LinkServerName = sDBName from ADCenter1.NDSPrimaryNew.dbo.tServerList where sServerType= '1 '

set @sql= 'SELECT @lMaxIndex = Max(lCompanyLogID) from ADCenter1. '+@LinkServerName+ '.dbo.tCompanyLog '

exec sp_executesql @sql,N '@lMaxIndex varchar(20) output ',@lMaxIndex output

print @lMaxIndex
------解决方案--------------------
try

declare @LinkServerName nvarchar(100) --数据库名
select @LinkServerName = sDBName from ADCenter1.NDSPrimaryNew.dbo.tServerList where sServerType= '1 '
--取得数据库名称 如:2007019

Declare @S Nvarchar(4000)
Select @S = N 'SELECT @lMaxIndex = Max(lCompanyLogID) from ADCenter1. ' + @LinkServerName + '.dbo.tCompanyLog '
EXEC sp_executesql @S, N '@lMaxIndex Int output ', @lMaxIndex output
print @lMaxIndex