Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a table variable without column definitions?

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)

like image 982
Ian Boyd Avatar asked Nov 10 '10 15:11

Ian Boyd


People also ask

How to declare a table variable in SQL?

When declaring table variables, the table variable must be the only variable being declared in the DECLARE statement. Is the name of the column in the table. Specifies that the column is a scalar data type. Is an expression defining the value of a computed column.

Can a table variable have a type of table?

However, its declaration statement has a type of table. Within the defining declaration for a table variable, you can specify column names that have data types and constraints.

Can a variable name be used in a column reference?

A column reference must always reference an existing column of the data model, or a column that has been generated using a table function assigning a specific name to it. Thus, a variable name cannot be used as a table name in a column reference.

What is the local variable type in the declaration statement?

The local variable type in the declaration statement is table. The declaration specifies a column name (id) and a column data type of nvarchar with a maximum length of 1.


2 Answers

Impossible. Citation from "books online":

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

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

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

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

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

PS: AFAIK insertion into any new table from "exec" results are impossible at all. Only to a table with predefined structre.

like image 172
Badiboy Avatar answered Oct 12 '22 13:10

Badiboy


You can't do it with table VARIABLES 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
like image 35
BClaydon Avatar answered Oct 12 '22 13:10

BClaydon