Transact SQL & Stored Procedure
Transact SQL & Stored Procedure
Transact SQL & Stored Procedure
What is Transact-SQL?
Programming language for SQL Server
Standard database manipulation language
SELECT, INSERT, UPDATE CREATE TABLE, CREATE PROCEDURE
Can write dynamic SQL to perform the same function as a procedural programming language do. ANSI 92 Compliant with Extensions
Transact-SQL Language
Data retrieval and modification (DML) Data definition language (DDF) Variables Control of flow
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
Variables
Support Two type of Variable.
Local Variable
Scope is limited to current batch Special names
All variable names must begin with @.
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.
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
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]]]