2

Usingset 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 可以做到这一点吗?

4

1 回答 1

1

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

于 2012-06-14T03:48:57.787 回答