Skip to main content

Table Variable - Sql Server

Microsoft first time introduce Table variable in sqlserver 2000. it is alternative to using temporary table, but has some difference. Table variable acts like general table to  store, update, delete and delete records. Table variable store in TempDB in sqlserver. I will explain TempDB in later.

Table variable declaration similar to CREATE TABLE Statement
Declaration :

DECLARE @MyProducts TABLE
(
       Id                 INT
      ,ProductName  VARCHAR(200)
      ,Price              numeric(18, 0)
)

DML Operation: DML operation as it is general table operation. You can use tablevariables in batches, stored procedures, and user-defined functions (UDFs). We can UPDATE records in our table variable as well as DELETE records.

--Insert statement
INSERT INTO @MyProducts VALUES(0,'Pran',20);
--Using Northwind database
INSERT INTO @MyProducts
SELECT ProductID,ProductName,UnitPrice FROM Products


SELECT * From @MyProducts;









--UPDATE statement
UPDATE @MyProducts
  SET Price = Price +5
WHERE Price < 15

--DELETE statement
DELETE FROM @MyProducts
WHERE Price < 15

 --Select Update data top 5
SELECT TOP 5 *
FROM @MyProducts WHERE Price < 20
ORDER BY ProductName DESC


















Other table features:

You can use UNIQUE, CHECK and also PRIMARKEY key constraint in Table variable.

DECLARE @MyProducts TABLE
(
 Id  INT
,ProductName  VARCHAR(200) UNIQUE
,Price  numeric(18, 0) CHECK (Price >10)
)
-- Unique constrain check
INSERT INTO @MyProducts VALUES (1,'Pran',20);

INSERT INTO @MyProducts VALUES (1,'Pran',24);








-- Chek constrain check
INSERT INTO @MyProducts VALUES (1,'Pran',20);
INSERT INTO @MyProducts VALUES (1,'Pen',6);










Limitations and restrictions:
  • Table variables does not have distribution statistics, theywill not trigger recompiles. Therefore, in many cases, the optimizer will build a query plan on the assumption that the table variable has no rows. For this reason, you should be cautious about using a table variable if you expect a larger number of rows (greater than 100).
  •  Table variables are not supported in the SQL Server optimizer's cost-based reasoning model. Therefore, they should not be used when cost-based choices are required to achieve an efficient query plan. Temporary tables are preferred when cost-based choices are required. This typically includes queries with joins, parallelism decisions, and index selection choices.
  • The table definition of a table variable cannot change after the DECLARE statement. Any ALTER TABLE query attempting to alter a table variable will fail with a syntax error. Along the same lines, you cannot use a table variable with SELECT INTO or INSERT EXEC queries. f you are using a table variable in a join, you will need to alias the table in order to execute the query.
  • Indexes cannot be created explicitly on table variables, and no statistics are kept on table variables. In some cases, performance may improve by using temporary tables instead, which support indexes and statistics.
  • CHECK constraints, DEFAULT values and computed columns in the table type declaration cannot call user-defined functions.
  • Assignment operation between table variables is not supported.
  • Because table variables have limited scope and are not part of the persistent database, they are not affected by transaction rollbacks.
  • Table variables cannot be altered after creation.

      Continue
         Used in Store Procedure:

        Used In User defined function:









Comments

Popular posts from this blog

What is RDBMS?

In our crucial programming world, RDBMS is stand for Relational Database Management Systems is based on the Relational Model that maintain data records and index in tables. Generally, the term "Relations" are maintained in RDMS.  In a relational database,store the data into collection of tables, which might be related by common fields (database table columns). RDBMS also provide relational operators to manipulate the data stored into the database tables. Most RDBMS use SQL as database query language. There are several objects are included in RDBMS like ,Indexes,Synonyms,Tables,Views Clusters,Constraints,Database links,Database triggers. Most popular RDBMS  are Oracle, MS-SqlServer, MySql,DB2. etc.

What are the difference between DDL, DML , DCL and TCL commands?

Database Command Types DDL Data Definition Language  (DDL) statements are used to define the database structure or schema.  -           CREATE - to create objects in the database -           ALTER - alters the structure of the database -           DROP - delete objects from the database -           TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed -           COMMENT - add comments to the data dictionary -           RENAME - rename an object DML Data Manipulation Language  (DML) statements are used for managing data in database. DML commands are not auto-committed. It means changes made by DML command are not permanent to d...

Identify and Delete duplicate Records in SQL Server

      S cenario: I have accumulated data into SQL Server database from three different servers (oracle, O2 and oracle) for a financial reporting. After data accumulated , we found more duplicate rows; business requirement was to remove all duplicate rows because of final data will be import to another system. For this purpose, I want to write script to find out duplicate rows from my table. Finally, I want to delete only duplicate rows not original row. Original row means if i have total 2 rows those same or duplicate, so I want to delete only one row that is duplicate. Let’s go............................ Step 1: Create a student Table below Script: CREATE TABLE [Students] (     [ID] [int] NULL,     [Name] [varchar] ( 50 ) NULL,     [address] [varchar] ( 50 ) NULL,     [contact] [varchar] ( 50 ) NULL,     [email] [varchar] ( 50 ) NULL ...