Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Table Variable using Existing Table Schema in Sql

I want to declare a Table Variable in my stored procedure using existing tables schema.

I have a Table, say TableA, which has about 30 columns. I want to declare a Table Variable using the same columns just as we declare a Temporary Table.

For instance, I can declare a Temporary Table using the schema like this:

SELECT TOP 0 * INTO #Temp_TableA FROM TableA

Can I similarly declare a Table Variable???

like image 253
Dinesh Saxena Avatar asked Aug 17 '15 09:08

Dinesh Saxena


People also ask

How do you DECLARE an existing table variable in SQL?

To declare a table variable, start the DECLARE statement. The name of table variable must start with at(@) sign. The TABLE keyword defines that used variable is a table variable. After the TABLE keyword, define column names and datatypes of the table variable in SQL Server.

How do I create a data table from an existing table?

A copy of an existing table can be created using a combination of the CREATE TABLE statement and the SELECT statement. The new table has the same column definitions. All columns or specific columns can be selected.

How do you DECLARE a variable in SQL query?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.


1 Answers

From MSDN:
No, table variable is a variable as name suggests so you need to declare it before you can use it like all other T-SQL variables and you need to use INSERT INTO

DECLARE @MyTable TABLE(
ID INT NOT NULL,
Data varchar(30) NOT NULL
);
INSERT INTO @MyTable
SELECT ID, data
From <table>

You can also use a temporary table in your stored procedure. Just add to the beginning of stored procedure this code:

if object_id('tempdb..#TableA') is not null drop table #TableA
like image 195
Roman Marusyk Avatar answered Sep 21 '22 17:09

Roman Marusyk