Monday, August 13, 2012

ISNULL(expressions)


In SQL 2008 r2, we have ISNULL() T-SQL predefined function to validate null values. If the retruning value is null then we can replace the variable with our predefined value.

Syntax: ISNULL(check_expression , replacement_value )

Eg:

DECLARE@IsPhoneNumber INT
SELECT @IsPhoneNumber = ISNULL(PhoneNumber,0) FROM dbo.tblAddress WHERE CustomerID= 1001
SELECT@IsPhoneNumber


The Result will be:
  • Prints '0' if the PhoneNumber value is NULL for given customer ID.
  • Prints 'PhoneNumber' if the given customerID holds phone number in that row.

Monday, August 6, 2012

How to OPEN & READ xml document in SQL 2008 R2:

In this post we are going to look into open and read an XMLdocument in SQL. In sql, we have some predefined stored procedures which hepls to prepare and remove XML files those are:

sp_xml_preparedocument,
sp_xml_removedocument

And OPENXML command executes XML handler to read and display the content. Find the below script to read and insert the XML data into a table.




CREATE  PROCEDURE [dbo].[xmlProducts]  
( 
@XmlOverView  NVARCHAR(MAX)  = null 
) 
AS   
BEGIN   
 
/***********************************************************************************   
** Desc                                      : SP to save Products details with XML documents
** Author          : Ramakrishna K
** Date                                      : 06/08/2012
***********************************************************************************/   
    
/***************************************   
* Standard SET statements.   
***************************************/   
SET NOCOUNT ON   
SET ANSI_PADDING ON   
SET ANSI_NULLS ON   
SET ANSI_WARNINGS ON   
SET CONCAT_NULL_YIELDS_NULL ON   
SET QUOTED_IDENTIFIER OFF   
    
 
/***************************************   
* Genric variables declaration
***************************************/   
DECLARE   
 @Msg  VARCHAR(1000),   -- To display message text   
 @Error  INT           -- Captuer errors        
      
SELECT   
 @Error = 0,    
 @Msg = ''   
 
/*************************************** 
*    SP declared variables 
***************************************/ 
DECLARE 
@TransactionExists BIT, 
@PID   INT,
@PName NVARCHAR(100),
@iDoc    INT

                        BEGIN TRY     
                           
                                                 --The number of BEGIN TRANSACTION statements that have occurred on the current connection.
                                                 IF @@TRANCOUNT > 0   
                                                                        SET @TransactionExists = 1   
                                                 ELSE   
                                                                        SET @TransactionExists = 0   
                            
                                                 IF @TransactionExists = 0   
                                                 BEGIN   
                                                                          --Initialise transaction      
                                                                          BEGIN TRANSACTION   
                                                 END   
                         
                                                 ---------------Section to save the product details into a table-------------------------- 
                          
                                                IF(@XmlOverView != NULL OR @XmlOverView != '') 
                                                BEGIN       
                                                                        EXECUTE sp_xml_preparedocument @iDoc OUTPUT, @XmlOverView 
                                                                                                                        INSERT INTO Production.xmlTest
                                                                                                                                                (PID
                                                                                                                                                                        ,PName
                                                                                                                        )  
                                                                                                                       
                                                                                                                        SELECT * FROM OPENXML(@iDoc, '/NewDataSet/Table',2) 
                                                                                                                                                                        WITH (ProductID  INT 
                                                                                                                                                                                                                        ,Name  NVARCHAR(500) 
                                                                                                                                                                        )  
                                                 
                                                                        EXECUTE sp_xml_removedocument @iDoc
                         
                                                  IF @TransactionExists = 0
                                                                          BEGIN    
                                                                                                COMMIT TRANSACTION    
                                                                                                RETURN (0)
                                                                          END
                                                END
                        END TRY
 
                        BEGIN CATCH
                                                IF @TransactionExists = 0   
                           ROLLBACK TRANSACTION   
                                                 SET @msg = Error_Message() 
                          RAISERROR (@msg,16,1) WITH NOWAIT 
                            
                          IF @Error = 0   
                           SET @Error = 1   
                          RETURN (@Error)
                        END CATCH    
END

Saturday, August 4, 2012

T-SQL Programming (SQL Server 2008 R2)

Programming with T-SQL

  • Stored Procedure
    • A stored procedure is a pre-compiled collection of transact-sql statements
    • A stored procedure encapsulates repetitive tasks
    • A stored procedure can accept input parameters and returns status value to indicate success or failure
    • A stored procedure can return multiple output parameters.
    • T-SQL statements that make up the body of a stored procedure can perform database operations like INSERT, DELETE, UPDATE, and SELECT as well as call another stored procedure(s).
    • To view the definition of stored procedure sp_helptext
    • Drop a single stored procedure DROP PROCEDURE procedure _name
    • Dropping multiple stored procedures DROP PROCEDURE procedure1, procedure2
    • Advantages:
      • Share application logic
      • Shield database schema details
      • Provide security mechanisms
      • Improve performance
        • Stored procedures implement many tasks as a series of T-SQL statements. Conditional logic can be applied to the results of the first T-SQL statements to determine which subsequent Transcat-SQL statements are executed.
      • Reduce network traffic
        • Rather than sending hundreds of Transact-SQL statements over the network, users can perform a complex operation by sending a single statement, which reduces the number of requests that pass between client and server.
        • The maximum size of a stored procedure is 128MB depending on available memory.
  • User Defined Functions
  • Working with Cursors
    • Cursors can be consider as named results sets which allow a user to move through each record one by one
  • Triggers
    • A trigger is a special type of stored procedure
    • A trigger is:
      • Associated with a table
      • Invoked automatically
      • Not called directly
      • Treated as part of the transaction that fired it

TSQL - Execution


Batch is one or more SQL server commands that are dispatched and executed together.

Command Line Execution Steps;

Step1: Parase commands and create the sequence tree

The command parser checks for proper syntax and translates the Transact-SQL commands into an internal format that can be operated on. The internal format is known as a sequence tree or query tree. The command parser handles these language events.

Step2: Compile the batch

An execution plan is generated from the sequence tree. The entire batch is compiled, queries are optimized, and security is checked. The execution plan contains the necessary steps to check and constrains that exist. If an after trigger exists for any data modification statement, the call to that trigger is appended to the execution plan for the statement.

Step3: Execute

During execution, each step of the execution plan is dispatched serially to a manager that's responsible for carrying out that type of command. A statement with an explicit BEGIN TRAN interacts directly with the transaction manager.

Step4: Recompile Execution Plans

It should be clear that the SQL code for routines persists in the database but execution plans don't. Execution plans are cached memory. But sometimes they can be invalidated and a new generated.

We can use GO or EXEC command to execute the batch files

Types of TSQL Statements:

Data Query Langauge (DQL)

  • Commands used to get data from the database and impose ordering upon it

Data Manipulation Language (DML)

  • Users move data into out of databases and also modify the data in the database
  • SELECT, INSERT, UPDATE, DELETE

Data Definition Language (DDL)

  • Is used to create, alter, and delete database objects
  • CREATE, ALTER, DROP, TRUNCATE

Data Control Language (DCL)

  • Consists of commands that control the user access to the database objects
  • GRANT, DENY, REVOKE

Transaction Control Language (TCL)

  • Commands allow the users to control transaction 
  • ROLLBACK, COMMIT