Metadata of Stored Procedure Result Set
I use Sql Server 2008开发者_运维问答.
I want to get the column names and data types of the result set of a stored proc. How can I do it? Something like INFORMATION_SCHEMA would be helpful.
From an application you can inspect the potential result set by first issuing SET FMTONLY ON. However this is being phased out in future version of SQL Server in favor of a much more robust metadata discovery mechanism. In the meantime, the best you're probably going to get is by using OPENQUERY against a loopback server. This assumes your stored procedure returns exactly one result set - if there are more than one, it isn't quite going to work.
For example:
EXEC master.dbo.sp_addlinkedserver
@server = 'LOOPBACK_SERVER',
@srvproduct = '',
@provider = 'SQLOLEDB',
@datasrc = @@SERVERNAME;
SELECT * INTO #foo
FROM OPENQUERY(LOOPBACK_SERVER, 'EXEC db_name.dbo.proc_name');
SELECT c.name, t.name, t.max_length, t.precision, t.scale
FROM tempdb.sys.columns AS c
INNER JOIN sys.types AS t
ON c.system_type_id = t.system_type_id
WHERE c.[object_id] = OBJECT_ID('tempdb..#foo');
DROP TABLE #foo;
Note this also assumes that you aren't using any CLR UDTs or alias types.
精彩评论