OPENQUERY
是一种可能的解决方案,使用FMTONLY OFF
. 将 exec 结果加载到虚拟表中,并将其列结构构建为字符串。下面以 sproc 形式演示此方法。假设分析的每个存储过程仅返回一个行集。
USE AdventureWorks
GO
CREATE PROCEDURE MySprocCols
@ExecStr NVARCHAR(1000)
AS
SET FMTONLY OFF;
SET NOCOUNT ON;
IF EXISTS (
SELECT 1
FROM sys.objects o
INNER JOIN sys.schemas s ON s.schema_id=o.schema_id
WHERE o.[type]='U'
AND s.name='dbo'
AND o.name='MyCols'
)
DROP TABLE dbo.MyCols;
DECLARE @SQL NVARCHAR(1000)
SET @SQL = '
SELECT TOP(0) *
INTO dbo.MyCols
FROM OPENQUERY(MyServer,'''+@ExecStr+''')';
EXEC SP_EXECUTESQL @SQL;
DECLARE @Cols VARCHAR(MAX) = '';
DECLARE @Del varchar(10) = ',';
SELECT @Cols += @Del + c.name + ''
FROM sys.objects o
JOIN sys.schemas s ON s.schema_id=o.schema_id
JOIN sys.columns c ON c.object_id=o.object_id
WHERE o.[type]='U'
AND s.name='dbo'
AND o.name='MyCols'
ORDER BY c.column_id
SET @Cols = STUFF(@Cols,1,LEN(@Del),'');
PRINT @Cols;
GO
EXEC dbo.MySprocCols 'exec AdventureWorks.dbo.uspGetBillOfMaterials 746,''''9/9/2000''''';
-- ^Must specify DB name here ^ Double-esc ^ all embedded single quotes
-- If you get an error like this:
--Msg 7411, Level 16, State 1, Line 2
--Server 'MyServer' is not configured for DATA ACCESS
-- ..you will first need to enable 'Data Access' through the following Surface Area Config command:
--exec sp_serveroption [MyServer],'Data Access','TRUE'
示例执行结果:
ProductAssemblyID,ComponentID,ComponentDesc,TotalQuantity,StandardCost,ListPrice,BOMLevel,RecursionLevel