You are on page 1of 19

Transact SQL & Stored Procedure

How to code in Microsoft SQL Server

Training Division New Delhi

What is Transact-SQL?
Programming language for SQL Server
Standard database manipulation language
SELECT, INSERT, UPDATE CREATE TABLE, CREATE PROCEDURE

Use of variable in SQL statement


Select @fname =firstname from customer_data

Program flow Control such as


IF-ELSE , CASE, WHILE LOOPS

Can write dynamic SQL to perform the same function as a procedural programming language do. ANSI 92 Compliant with Extensions

Why would I use it?


Reporting
Let server do the Computation Only return final data for report/Program

Business Logic Batch processing Server side processing

Where do I write the code?


ISQL/OSQL (script as a text file) Query Analyzer Stored Procedure (Database) Triggers ( tables)

Transact-SQL Language
Data retrieval and modification (DML) Data definition language (DDF) Variables Control of flow

Data Definition Language


Language to create Database Create Database Mydb Alter Database mydb Drop Database mydb Language to create tables, indexes, etc. CREATE TABLE customer_data (cutomer_id samllint, first_name char(20), last_name char(20), phone char(10)) ALTER table Drop Table

Data Retrieval and Modification


Retrieval
SELECT
JOINS and FROM WHERE GROUP BY, HAVING, and Aggregate Functions ORDER BY

PRINT
declare @xx char(10) select @xx =first_name from customer_data where customer_id=1234 print @xx
PRINT Hello World PRINT My SQL Server Version is + @@version

Data Retrieval and Modification


Modification
INSERT UPDATE DELETE

Variables
Support Two type of Variable.

Local Variable
Scope is limited to current batch Special names
All variable names must begin with @.

All variables must be Declared


DECLARE @X INTEGER DECLARE @XX AS CHAR(20)

Setting variables is just like retrieving data


SELECT @X = 99 SELECT @XX=RAJENDRA SET @XX =RAJENDRA

Variables
Global Variables
SQL Server creates and maintains Not user definable Have two @ symbols Examples
@@Fetch_Status @@Rowcount @@SPID @@TranCount @@Servername @@version
Select @@version select @@servername

Datatypes
Binary (binary, varbinary) Character (char, varchar) Datetime Floating Point (decimal, numeric, float, real) Integer (int, smallint, tinyint) Monetary (money, smallmoney) Bit Timestamp User-defined datatypes Text Image

Control of Flow
IF...ELSE
Can be basic or complex IF. Unlimited embedding of IFs

WHILE
Basic structure to loop until condition is met.

GOTO BEGINEND RETURN


Allows integer values to be passed out of procedure back to calling procedure

Expressions and built in functions


Operators System functions
ISNULL

Wild cards and the LIKE operator

Stored Procedures
A stored procedure consists of one or more SQL statements that perform a unit of work When Executed it compiled into an execution plan which contains two parts; one part that contains the code to be executed, and one part that contains the variables and parameters that are to be used by the code.
Can accept variables Return values

Multiple users and programs can execute the same stored procedures Can call other procedures
EXEC spDoSomething

Stored Procedure
Maintenance becomes easier because we can change one stored procedure and it immediately becomes effective for all users and programs. Once a stored procedure is executed, it is placed in SQL Server cache. This means that subsequent executions are executed from cache . Greater Security. Low Network Traffic

Stored Procedure
Create Stored Procedure
Create procedure procedure_name (@parameter_name, datatype, length, output) As SQL Statement

Execute a Stored Procedure


Execute procedure_name (@parameter_name=value OR @parameter_name=@variable output) With recompile

Calling a Stored Procedure


Set Parameter=command.createParameter (Name, type, Direction, size, value)
Name=The Name of the Parameter Type=The Data Type of the Parameter Direction= adParamInput adParamOutput adparamInputOutput adparamReturnValue Size=The Size of the Parameter Value=The value of the Parameter

System stored procedures


sp_who sp_help sp_lock sp_password sp_rename

Cursors
Cursors allow a developer to process records one at a time.
Similar to ADO or RDO processing in VB or Access Very flexible - but theres a catch.
Usually less efficient than regular SQL queries.
DECLARE cursor_name CURSOR [LOCAL | GLOBAL] [FORWARD_ONLY | SCROLL] [STATIC | KEYSET | DYNAMIC | FAST_FORWARD] [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC] [TYPE_WARNING] FOR select_statement [FOR UPDATE [OF column_name [,...n]]]

You might also like