Declare a table variable without defining columns?

Is there a way in SQL Server to declare a table variable without knowing the table definitions?

Exempli gratia:

DECLARE @Results TABLE INSERT INTO @Results EXEC MyProc @param1 = @myValue 

or

 DECLARE @Results TABLE SELECT INTO @Results EXEC MyProc @param1 = @myValue 

or

 DECLARE @Results TABLE EXEC MyProc @param1 = @myValue INTO @Results 

or

 DECLARE @Results TABLE EXEC INTO @Results MyProc @param1 = @myValue 

or

 DECLARE @Results TABLE SELECT * FROM EXEC MyProc @param1 = @myValue INTO @Results 

or

 DECLARE @Results TABLE SELECT * INTO @Results FROM EXEC MyProc @param1 = @myValue 

or

 DECLARE @Results TABLE SELECT * INTO @Results EXEC MyProc @param1 = @myValue 

(you get the idea)

+4
source share
2 answers

impossible. Quote from "books online":

===============

Syntax Note. Use DECLARE @local_variable to declare type table variables.

 table_type_definition ::= TABLE ( { column_definition | table_constraint } [ ,...n ] ) 

===============

"(" at least one column definition and ")" are syntactically required.

PS: Insert AFAIK into any new table from the results of "exec" is generally impossible. Only for a table with a predefined structure.

+6
source

You cannot do this with VARIABLES tables, but you can do it with TEMP tables.

 -- Drop the table, if it exists IF OBJECT_ID(N'tempdb.dbo.#tmpMyTable',N'U') IS NOT NULL DROP TABLE #tmpMyTable SELECT ColumnA, ColumnB INTO #tmpMyTable FROM MyTable -- Then clean up after yourself DROP TABLE #tmpMyTable 
0
source

All Articles