SET NOCOUNT ON;
DECLARE @sql NVARCHAR(MAX)
--,@DBName VARCHAR(30)
--SET @jobNumber=417133
--SELECT @DBName = DataBaseName,'tdis', @server = '[' + isnull(server,'s-portaldb1') + ']'
--from tdLogging.dbo.tblJobDbLookup where jobnumber = @jobNumber
DROP TABLE #Actual
CREATE TABLE #Actual (
jobnumber INT
,firstNameCounts VARCHAR(25)
,lastNameCounts VARCHAR(25)
,address1Counts VARCHAR(25)
,address2Counts VARCHAR(25)
,cityCounts VARCHAR(25)
,stateCounts VARCHAR(25)
,zipCounts VARCHAR(25)
,inHomeDateCounts VARCHAR(25)
)
SET @sql = 'INSERT INTO #actual (jobnumber,firstNameCounts,lastNameCounts , address1Counts, address2Counts, cityCounts, stateCounts, zipCounts, inHomeDateCounts) '
SET @sql = @sql + ' Select s.jobnumber, count(s.firstName) AS [firstNameCounts], Count (s.lastName) AS [lastNameCounts], Count (s.Address1) As [address1Counts], Count (s.address2)-Count (address2) AS '
SET @sql = @sql + ' [address2Counts], Count (s.City) AS [cityCounts], Count (s.State) AS [stateCounts], Count (s.Zip) AS [zipCounts], Count (jb.inHomeDate) AS [inHomeDateCounts] '
SET @sql = @sql + ' From [s-portaldb1].[tdis_417133].[dbo].[tblStandardFinal] s '
SET @sql = @sql + ' INNER JOIN [s-printstream].[tdSchedule2].[dbo].[tblJobTicketActions] jb '
SET @sql = @sql + ' ON jb.psFlagJobNumber = s.jobNumber '
SET @sql = @sql + ' where jobNumber = @jobNumber '
SET @sql = @sql + ' group by jobNumber '
PRINT @SQL
EXEC sp_executesql @sql
,N'@JobNumber Varchar(25)'
,@JobNumber = 417133;
SELECT *
FROM #Actual
我正在尝试让这段代码动态运行,我想让“[s-portaldb1]。[tdis_417133]”在运行中意味着动态运行。
任何帮助将不胜感激。谢谢
答案 0 :(得分:0)
不确定我知道“运行中”是什么意思,但是如果你想在动态SQL中使服务器名称动态化,只需为服务器名称添加一个参数,然后使用类似的东西将其引入SQL以下内容:
DECLARE @ServerName varchar(100) = '[s-portaldb1].[tdis_417133]'
SET @sql = @sql + ' From ' + @Servername + '.[dbo].[tblStandardFinal] s '