I’m working with stored procedures in SQL Server 2008 and I’ve come to learn that I have to INSERT INTO a temp table that has been predefined in order to work with the data. That’s fine, except how do I figure out how to define my temp table, if I’m not the one that wrote the stored procedure other than listing its definition and reading through the code?
For example, what would my temporary table look like for `EXEC sp_stored_procedure’? That is a simple stored procedure, and I could probably guess at the data types, but it seems there must be a way to just read the type and length of the columns returned from executing the procedure.
So let’s say you have a stored procedure in tempdb:
There is a quite convoluted way you can go about determining the metadata that the stored procedure will output. There are several caveats, including the procedure can only output a single result set, and that a best guess will be made about the data type if it can’t be determined precisely. It requires the use of
OPENQUERYand a loopback linked server with the'DATA ACCESS'property set to true. You can check sys.servers to see if you already have a valid server, but let’s just create one manually calledloopback:Now that you can query this as a linked server, you can use the result of any query (including a stored procedure call) as a regular
SELECT. So you can do this (note that the database prefix is important, otherwise you will get error 11529 and 2812):If we can perform a
SELECT *, we can also perform aSELECT * INTO:And once that #tmp table exists, we can determine the metadata by saying (assuming SQL Server 2005 or greater):
(If you’re using SQL Server 2000, you can do something similar with syscolumns, but I don’t have a 2000 instance handy to validate an equivalent query.)
Results:
In Denali, this will be much, much, much easier. Again there is still a limitation of the first result set but you don’t have to set up a linked server and jump through all those hoops. You can just say:
Results:
Until Denali, I suggest it would be easier to just roll up your sleeves and figure out the data types on your own. Not just because it’s tedious to go through the above steps, but also because you are far more likely to make a correct (or at least more accurate) guess than the engine will, since the data type guesses the engine makes will be based on runtime output, without any external knowledge of the domain of possible values. This factor will remain true in Denali as well, so don’t get the impression that the new metadata discovery features are a be-all end-all, they just make the above a bit less tedious.
Oh and for some other potential gotchas with
OPENQUERY, see Erland Sommarskog’s article here:http://www.sommarskog.se/share_data.html#OPENQUERY