Wednesday, January 16, 2013

Temp Tables Vs Table Variables

It’s always a tricky decision while thinking about using Temp Table of Table Variable. Let’s look into this article to check the differences between these two.

#Temp tables are the regular SQL tables that are defined and stored in TempDB database of Sql server. It is more or less equal to permanent tables but the only difference with #table is that could not have foreign key over it.

While going through the rest of the article we will look into the various important aspects of both the objects i.e. (#table & @table variable).


How to create / declare policy:
#Table: Temp tables could be created by writing table creation script or by writing the insert into script. Both the ways Process ID specific #table get created into TempDB database.

@Table Variable: Table variables can only be created by specifying Declare @name as Table syntax. Creating a table variable is little different from Create table syntax because we have to declare table variable like the way we declare local variables.

Note: Table variables cannot be created with the Select into syntax.

Lifespan of #table & @table variable:
Temporary table are of two type namely #table (Local temporary table) & ##table (Global temporary table). The lifespan of local temporary table is limited till the specific user session. Explaining in brief whenever any Process ID creates a temporary table then that #table gets created into TempDB database with that Process ID Specific access rights. If some other process ID also creates the #table with the same name then also without creating any mismatch between the names Sql engines creates the temp table for another user & keeps them unique for each process use.

Lifespan of #table is limited till the user does not forcefully drop the table or close the connection. Once the connection is closed or #table is dropped the #table gets flushed from the TempDB database.

@Table Variable: The lifespan of table variables are limited till the execution of process or execution of queries. Once the execution of queries ends the data & table architecture gets flushed from the Sql database memory.

Performance Parameter:

While comparing on the performance platform we need to discuss various parameters.

#Table: #tables are physically stored on system drive due to which it does not use the system buffer the way table variable uses. Index creation is permitted on #table which enables the user to fetch the data with the use of Index in faster manner. #table can be used to store huge data without harming the system performance. The only burden which #table put’s on system is its Read & Write operation.
#table participate in transactions so whenever the transaction related request occurs #tables behave accurately & revert back to the original positions.

@Table Variable: A myth which is associated with @table variable is that it should be used for the smaller data size operation because it uses the Sql buffer for storing & managing data which may cause the performance issues while working with huge data size.
@table variable do not participate in transactions & do not behave as per the transaction rules.

Note: #Tables causes a recompilation due to which a same execution plan could not be used. The cost of Read / Write operation of table variables are less as compared to #tables due to which it shows good performance while we need to write & then read data from processed table.

Thursday, January 10, 2013

Merits of Using Stored Procedure over Ad-Hoc queries

Stored procedure is a set of Structured Query Language statements with a user defined name. Stored procedures are physically stored within the database in precompiled form for ready to use purpose allowing applications to use it by any number of times & by any number of programs.

Ad hoc queries are the open queries which are written at application side or in SSSMS generally for requirement specific purpose.

Problems of Ad-hoc Queries:
As mentioned in description ad-hoc queries are open queries which are generally used for some specific requirement. The major demerit of using ad-hoc queries are,

Ad-hoc queries are not stored in Sql server causing no pre-stored query plan due to which whenever the ad-hoc is run the first thing Sql engine does is that it generates the executions plan every time where in case of Stored procedures a precompiled plan is ready used. Each time plan generation activity causes the execution duration & delay in result presentation.

Ad hoc queries can kill performance and some time it is hard to control complex logics through these ad hoc queries. Store procedures are the best choice to accomplish these data processes. Let’s see some important information about the same,

·         Reduce Network Traffic: Excessive network traffic is a big performance killer in production databases. In a case where users are frequently pushing request to database server through some client application (because of ad hoc queries) this may cause a excessive network traffic because the complete ad-hoc request will hit the server via network & depending on the size of query & data size the network will be used in same proportion. In this situation Store Procedures will help in reducing such network traffic by holding group of statements and returning required result with a single call.
Stored procedures are stored in database system & can be bring into use via calling by name & appropriate procedures.

Note:  Lengthy transactions in store procedures should be avoided to prevent lock problems. In real world this have been observed that while using transactions into procedures most of the developers put the complete script into transactions (some selects from huge tables etc.) which causes the other objects to be busy during the complete execution of stored procedure.

·         Privilege based execution
Stored procedures can be grant to be executed as per the user privileges. Users can be restricted from having access to read/write to tables directly in database by using store procedures. Only developer of store procedure require specific privileges while creating a store procedure but to execute these store procedures client of application only need execute privileges.

·         Re-use of Execution Plan
As mentioned in fist point Store procedures are compiled once and resultant execution plan are utilized for future executions. This results in tremendous performance boosts when store procedures are called repeatedly.

·         Efficient Re-use of Code
Commonly used store procedures can be effectively used for different projects.
For example, In case of financial application the logic for printing the amount on various documents can be used on various instances just by calling the concerned stored procedure by providing the proper parameter.

·         Ease of Maintenance
     In real world change in business rules defined for a project, over a time is normal. If such business rules are controlled with in store procedures rather than ad-hoc then it is very for the maintenance. In this case developer need to make changes in every piece of code & recompile.


Wednesday, January 9, 2013

How to find the last database backup restore information

Some Times we need to find the date/Time information when the database backup was restored on some database. In this situation below mentioned query will help a lot in finding this information including the database name, Restore date etc.


SELECT
rs.destination_database_name, rs.restore_date, bs.backup_start_date, bs.backup_finish_date,
bs.database_name as source_database_name, bmf.physical_device_name as backup_file_used_for_restore FROM msdb..restorehistory rs INNER JOIN msdb..backupset bs
ON rs.backup_set_id = bs.backup_set_id
INNER JOIN msdb..backupmediafamily bmf ON bs.media_set_id = bmf.media_set_id ORDER BY rs.restore_date DESC;

Properties of Relational Tables in Sql Server


Sql Server database is a complete RDBMS system as it follows all 12 rules of CODD which defines a database system as RDBMS. For making a RDBMS or DMBS system proper as database design for table should also be in a proper defined manner for the ease of access.


There are 6 properties of Relational Tables in sql server and they are as follow,


1) Values Are Atomic
This property implies that columns in a relational table are not repeating group. The key benefit of the one value property is that it simplifies data manipulation logic. This property of tables are even referred to be in the “first normal form” (1NF) of normalisation.


2) Referencing Column Values Are of the Same Kind
In relational terms this means that all values in a column belong to same type. This property simplifies data access because developers and users can be certain of the type of data contained in a given column. It also simplifies data validation. Because all values are from the same domain, the domain can be defined and enforced with the Data Definition Language (DDL) of the database software.


3) Each Row is Unique
This property ensures that no two rows in a relational table are identical. there is at least one column, or set of columns, the values of which uniquely identify each row in the table. Such columns are called primary keys. This property guarantees that every row in a relational table is meaningful and that a specific row can be identified by specifying the primary key value.


4) The Sequence of Columns is Insignificant
This property states that the ordering of the columns in the relational table has no meaning. Columns can be retrieved in any order and in various sequences. The benefit of this property is that it enables many users to share the same table without concern of how the table is organized. It also permits the physical structure of the database to change without affecting the relational tables.


5) The Sequence of Rows is Insignificant
This property is analogous the one above but applies to rows instead of columns. The main benefit is that the rows of a relational table can be retrieved in different order and sequences. Adding information to a relational table is simplified and does not affect existing queries.


6) Each Column Has a Unique Name
Any database system does not allow duplicate column names in database table however this is defined as a property that column name need to be unique within the table.