T-SQL - 如何使用FMTONLY从存储过程以编程方式获取列数据

时间:2012-06-14 02:30:59

标签: tsql stored-procedures metadata

使用set FMTONLY on;允许我查看从SSMS中的存储过程返回的列,但是如果我想以编程方式获取过程中的那些列名并对它们执行某些操作,该怎么办?

基本上,我想要实现的是这样......

declare @columns nvarchar(max) = (
    select name + ', '
    from sys.columns
    where object_id = OBJECT_ID('my_stored_procedure')
    for xml path(''));

显然,这不起作用。这可以用T-SQL吗?

1 个答案:

答案 0 :(得分:1)

OPENQUERY是一种可能的解决方案,FMTONLY OFF。将exec结果加载到虚拟表中,并将其列结构构建为字符串。以下以sproc形式演示了这种方法。假设每个分析的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