Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get column names/types returned from a stored procedure

Is there a way via metadata (Information_Schema, perhaps?) to get a list of the columns a sproc will return? I'm trying to automate some code generation and that would help tremendously...

like image 524
Caveatrob Avatar asked Sep 19 '10 23:09

Caveatrob


People also ask

How can get column name in stored procedure in SQL Server?

sp_help procedure The sp_help procedure is used to get information about a current database object. The database object may be a table, view or stored procedure. To get a column name of a table we use sp_help with the name of the object or table name. sp_help will return all the column names of the object.

How can get column value from stored procedure in SQL?

The only way to work with the results of a stored procedure in T-SQL is to use the INSERT INTO ... EXEC syntax. That gives you the option of inserting into a temp table or a table variable and from there selecting the data you need. That requires knowing the table definition.

Can procedure have return type?

A stored procedure does not have a return value but can optionally take input, output, or input-output parameters. A stored procedure can return output through any output or input-output parameter.

How do I get column names in SQL?

In SQL Server, you can select COLUMN_NAME from INFORMATION_SCHEMA. COLUMNS .


2 Answers

Unless you're prepared to parse the contents of ROUTINE_DEFINITION in INFORMATION_SCHEMA.ROUTINES, then your best bet will be to execute the procedures, and read the column information from the records returned.

In .NET you can do this by reading the results of the stored procedure into a DataTable and querying the Columns property.

The reason there's no easy way to do this is a stored procedure could potentially return different result sets based on the parameters. There's no fixed result set format like there is with user defined functions.

Edit

As mentioned in the other answer, you will need to use SET FMTONLY ON to ensure no data is returned. There are some situations where SET FMTONLY won't work, e.g. when using #temp tables in your stored procedures, but there is a workaround.

like image 86
Bennor McCarthy Avatar answered Sep 29 '22 12:09

Bennor McCarthy


I just ran Profiler to see how Visual Studio does this for the strongly typed dataset drag and drop.

This is the code it sent.

 SET NO_BROWSETABLE ON; 
 SET FMTONLY ON;

exec dbo.aspnet_Roles_GetAllRoles @ApplicationName=NULL

So I presume there might not be any "more official" way of doing it.

Obviously you would need to bear in mind that a single stored procedure might return multiple result sets or different result sets dependant on the parameters passed.

For people on 2012+ another approach might be to use sp_describe_first_result_set

like image 40
Martin Smith Avatar answered Sep 29 '22 11:09

Martin Smith