执行下面的查询时,如果我使用PRINT
它会正确打印。我可以复制并粘贴打印的代码并执行它。但是,如果我使用 EXEC,则会收到以下错误:
有没有办法简化我正在做的事情?为什么 SQLPRINT
和 SQLEXEC
会提供这两个截然不同的结果集?
DECLARE @TableName as NVARCHAR(250), @SQL as VARCHAR(MAX);
DECLARE @TableCursor as CURSOR;
SET @TableCursor = CURSOR FOR
SELECT sobjects.name
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U'
AND name like 'HISTORY_MasterList_%'
ORDER BY sobjects.name
OPEN @TableCursor;
FETCH NEXT FROM @TableCursor INTO @TableName;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @SQL ='select '''+ @TableName +''', 0
Union All
select All ''Server Count'',count(1) from ['+ @TableName +']
Union All
select All ''Server Cores'',sum(convert(decimal(18,0),cores)) from ['+ @TableName +']
Union All
select ''Production Servers'',count(1) from ['+ @TableName +'] where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
Union All
select ''Production Cores'', sum(convert(decimal(18,0),cores)) from ['+ @TableName +']
where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
Union All
select ''Production Server Count after filtering out passive/failover servers'', count(1) from
(select distinct m.ServerName
from ['+ @TableName +'] m
inner join [SQLEnv].[dbo].[vwManView] v on m.ServerName = v.ServerName
where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
and unit <> 0) aa
Union All
select ''Production Server Cores after filtering out passive/failover servers'', sum(convert(decimal(18,0),cores)) from(
select distinct m.ServerName, m.Cores
from ['+ @TableName +'] m
inner join [SQLEnv].[dbo].[vwManView] v on m.ServerName = v.ServerName
where Classification in (''Prod'',''Production'',''Prd'',''Unknown'')
and unit <> 0) aa
Union All
select ''Non-Prod SQL Instances downgraded to Developer Edition'',count(1) from ['+ @TableName +'] where ''InstanceStatus'' like ''Downgrade%''
Union All
select ''Non-Prod SQL Instance Core Count downgraded to Developer Edition'',sum(convert(decimal(18,0),cores)) from ['+ @TableName +'] where ''InstanceStatus'' like ''Downgrade%''
Union All
select ''Non-Prod VMs moved from Prod Environments'', count(1) from ['+ @TableName +'] where ServerStatus like ''VM Moved/right sized from Prod Env to NonProd''
Union All
select ''Non-Prod VMs TO BE moved from Prod Environments'', count(1) from ['+ @TableName +'] where ServerStatus like ''Sent for V2V - non prod split''
'
EXEC @SQL
FETCH NEXT FROM @TableCursor INTO @TableName;
END
CLOSE @TableCursor;
DEALLOCATE @TableCursor;
错误是这样说的
...it is not a valid identifier
。当您传递EXEC @SQL
时,它期望它@sql
代表存储过程(或标量函数)的名称。因此错误消息:...it is not a valid identifier
.如果你想执行一个文本,动态传递,你应该把那个文本封装在里面
( )
,比如EXEC (@SQL)
.