Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating table variable in SQL server 2008 R2

what is table variable? And how to create a table variable (virtual in-memory table) with columns that match the existing Stored procedure resultset.

I executed the procedure and after executing it, the column names are known to me. But do i have to declare the same data type of the columns as it was in stored procedure?

EDIT: I tried this

DECLARE @Table TABLE(  name varchar(30) NOT NULL,  location varchar(30) NOT NULL  );   INSERT @Table  SELECT name, location FROM  Exec SPROC @param , @param 
like image 317
Pankaj Avatar asked Mar 13 '12 04:03

Pankaj


People also ask

How do you create a variable in a table 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 you DECLARE a variable in a table in SQL Server?

If we want to declare a table variable, we have to start the DECLARE statement which is similar to local variables. The name of the local variable must start with at(@) sign. The TABLE keyword specifies that this variable is a table variable.

What is #temp table and @table variable in SQL Server?

Temporary Tables are physically created in the tempdb database. These tables act as the normal table and also can have constraints, index like normal tables. Table Variable acts like a variable and exists for a particular batch of query execution. It gets dropped once it comes out of batch.


1 Answers

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50)) 

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL   DROP TABLE #test  

Hope this makes sense !

like image 104
mangeshkt Avatar answered Sep 22 '22 17:09

mangeshkt