Read more: http://www.blogsmonetize.com/2010/10/how-to-use-syntax-highlighter-3083-in.html#ixzz1DHzvEgBA

Saturday, December 18, 2010

Table variable myths

There are always some myths around the table variable:
1. Table variables works with only memory.
- It is wrong understanding that the table varibles works only with memory. If table variables are populated with more records, it spills to the temp DB and works as Temperory tables. We need to make sure if the records are less and enough to do the operations in memory, can easily go with the table variable considering the basic differences with temperory table.

2. Table variables can not be indexed at all.
- Many of SQL developers think that the table variable can not be indexed. In truth, it can be very well at the declaration part as below:
DECLARE @Test TABLE (
ID INT NOT NULL PRIMARY KEY,
IndexableColumn1 INT,
IndexableColumn2 DATETIME,
IndexableColumn3 VARCHAR(10),
UNIQUE (IndexableColumn1,ID),
UNIQUE (IndexableColumn2,ID),
UNIQUE (IndexableColumn3, IndexableColumn2, ID)
)
3. Changes to table variables are not logged.
- Even table variables are not part of the transactions(can not be a partof rollback; no effect), it logs the operations. This is for the main reason to avoid any violation to the primary/unique key constraints. Say, inserting a bunch of records to a table varible breaks at the mid of the operations, it has to delete the records from that table variable(Atomicity concept).

Reference:
http://sqlinthewild.co.za/index.php/2010/10/12/a-trio-of-table-variables/#more-687

No comments: