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)
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With