Wednesday, May 28, 2008

Declaration Table vs Temporary Table

When i got the interview a couple days ago, the interviewer was asking me about declaration and temporary table difference. well, before he asked me about it, i've googled about it on the internet. and i found the answer about the difference between declaration and temporary table is "How to use it". What is that mean? well, it's about the data. when you are working with huge data, you can use temporarty table and when you are working with small data, you can use declaration table. Why? because the temporary table can be indexed and declaration table isn't. But .... how big is it? sometimes 10,0000 is a big data but when you are working with database that has Tera Bytes, maybe 10,000 data is a small.

And, the interviewer explained it to me what is the difference between declaration and temporary table. he said the declaration table can only executed on single batch and the temporary table can be executed on active session -this is i've already known. Well, i will give the example. Here are the code:

/* Declaration Table */
DECLARE @TABLE TABLE
(
    FIELD_A INT NOT NULL PRIMARY KEY,
    FIELD_B VARCHAR(25) NULL
)

SELECT * FROM @TABLE
GO
SELECT * FROM @TABLE

/* Temporary Table */
CREATE TABLE #TABLE
(
    FIELD_A INT NOT NULL PRIMARY KEY,
    FIELD_B VARCHAR(25) NULL
)
SELECT * FROM #TABLE
GO
SELECT * FROM #TABLE

Well, on the first code. we found the error message "Must declare the table variable "@TABLE"". Why, cause after GO statement, the batch is over and change to another batch. And we must create it again. And on the second code, the code will running well, cause the temporary table running on one active seassion. And that is the difference about declaration and temporary table that i know.

About performance, many people said that not quite difference between declaration and temporary. even when we are using index on temporary table. So, if you intend to use the declaration table, using it when the data needs only on the batch query and using the temporary table when the data needs on the global area on single batch.

No comments: