31

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
7
  • 6
    Just a word of warning: A table variable isn't guaranteed to be in memory. That's a myth. Commented Mar 13, 2012 at 5:13
  • Can you include the code you have so far so we can answer your question? Commented Mar 13, 2012 at 5:14
  • @JohnFx I havnn't executed code for the creation of table variable. I made a stored procedure and after executing it i got some column names, now i want those column names to be stored in table variable. And if it is not always in memory then how can i find it in my database, Sorry for troubling i am new on SQL. Please Help. Commented Mar 13, 2012 at 5:20
  • To clarify: It might be on disk (depending on a number of factors) instead of memory, but that doesn't mean it will be a table that you can query directly. If you need that functionality go with a temp table instead of a table variable. Commented Mar 13, 2012 at 15:09
  • possible duplicate of SQL Server - SELECT FROM stored procedure Commented Mar 13, 2012 at 15:13

1 Answer 1

31

@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 !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.