Transact-SQL Introduction

Preview:

DESCRIPTION

Transact-SQL Introduction. ISYS 464. T-SQL. - PowerPoint PPT Presentation

Citation preview

Transact-SQL Introduction

ISYS 464

T-SQL• Transact-SQL is Microsoft's and Sybase's

proprietary extension to the SQL language. Microsoft's implementation ships in the Microsoft SQL Server product. Sybase uses the language in its Adaptive Server Enterprise, the successor to Sybase SQL Server. SQL has been enhanced with additional features such as: – Control-of-flow language – Local variables – Various support functions for string processing, date

processing, mathematics, etc.

• T-SQL on-line reference:– http://msdn2.microsoft.com/en-us/library/ms189826.aspx

Stored Procedure

• System procedures are batch files that are stored in the database and then executes by name. They provide secure interface to the data.– System procedures

• Sp_help• Sp_databases• Sp-tables• Sp-columns tableName• Sp_stored_procedures

– User-defined procedures• To run a procedure:

– Exec procedureName

Listing Tables and Columns

• Use system procedure sp_help– Exec sp_help

• Select tables from the SysObjects Table:– Select * from sysobjects where type=‘U’;

• Type – U – user tables– V – views– S – system tables– TR – triggers– P – stored procedure– K – primary key– F – foreign key

• To show the names of columns:– Select * from customer where 1=2;

SELECT Dialect

• Select 1+1;

• Select 'my name is',cname from customer;

• select getdate();• select datepart(yy, getdate()),

datepart(mm,getdate()), datepart(dd,getdate())

• select convert(varchar(40),getdate(),9);

SELECT with CASE

select cid,cname,(case when rating='A' then 'Excellent'when rating='B' then 'Good'else'Bad'end) As Greeting

from customer;

Case with Update Statement

Update CustomerSet Credit = Case

When Credit < 500 then Credit*1.15Else Credit * 1.10End

Top N Analysis

SELECT Top 3 Student.SID, Student.SName, Student.Major, Student.GPA, Student.SEXFROM StudentOrder By GPA Desc;

Batch Programming• Declare local variables (last only in the

batch it is declared):– Declare @counter int

• Assigning value to a variable:– Select @counter = 1

• Assigning variable a value from a table:– Declare @custrating char(1)– Select @custrating = rating from customer

where cid=‘C1’;

Global Variables

• @@error: If not zero, an error occurred

• @@rowcount; the number of records affected by the last statement

If Statement

• If :– If @custrating = ‘A’

• Print ‘Excellent’

– Else• Print ‘Not good’

• Use Begin End to group statements after an IF or WHILE:– If @custrating = ‘A’ Begin

• Print ‘Excellent’• Select @counter = @counter + 1• End

WHILE Statement

• Declare @counter int

• select @counter = 1

• while @counter < 5 begin

• print @counter

• select @counter = @counter + 1

• end

Cursor

• A cursor is a pointer to a set of records returned by a SQL statement. It enables you to take a set of records and deal with it on a row-by-row basis.

Defining and Using CursorsStep 1: Declare cursor:

– Declare cursorname Cursor – Read_Only– For SQL statement

• Ex: Declare ACustomer CursorRead_Only

For select * from customer where rating=‘a’

Step 2: Open cursor:OPEN cursorname

Example: Open Acustomer

Step 3: Fetch data into variables:FETCH Next From cursorname into list of local variables

Example: Fetch Next ACustomer into @CustID, @CustName, @CustCity, @CustRating

Use @@Fetch_Status to test if record exist. If @@Fetch_Status = 0, fetching is successful

Step 4: CLOSE cursorname

Step 5: Deallocate cursor

deallocate Acustomer

Cursor ExampleUse MySQLDBDeclare ACustomer Cursor Read_OnlyFor Select * from customer where rating='A'/* SQL 92: For Select * from customer where rating='A' *//*for read only */Declare @CustID char(3), @CustName char(20), @CustCity char(20)Declare @CustRating char(1),@CustCredit decimal(7,2)Open ACustomerFetch Next From ACustomer Into @CustID, @CustName,@CustCity,@CustRating,@CustCreditWhile @@Fetch_Status=0 Begin

If @CustCredit > 1000 Select @CustName, 'Excellent customer'

elseselect @CustName, 'Regular customer'

Fetch Next From ACustomer Into @CustID, @CustName,@CustCity,@Custrating,@CustCredit

endClose Acustomerdeallocate Acustomer

Update Cursor ExampleDeclare UpdateCustomer CursorFor Select * from customer where rating='A'For Update of CreditDeclare @CustID char(3), @CustName char(20), @CustCity char(20)Declare @CustRating char(1),@CustCredit numeric(7,2)Open UpdateCustomerFetch Next From UpdateCustomer Into @CustID, @CustName,@CustCity,@CustRating,@CustCreditWhile @@Fetch_Status=0 Begin

If @CustCredit > 1000 Update CustomerSet Credit = Credit * 1.15Where Current of UpdateCustomer

elseUpdate CustomerSet Credit = Credit * 1.1Where Current of UpdateCustomer

Fetch Next From UpdateCustomer Into @CustID, @CustName,@CustCity,@Custrating,@CustCredit

endClose UpdateCustomerDeallocate UpdateCustomer

Stored Procedures

• Stored procedures are batches that can be executed by name.

• Benefits:– Enhanced control of data– Straightforward access to complex data

operations– Improved performance

Procedure with Input Parameters

CREATE PROCEDURE AddNewCustomer(@cid char(5),@cname char(20),@city char(20),@rating char(1),@credit numeric)

ASinsert into Customer values (@cid,@cname,@city,@rating,@credit)

RETURN

Command to call the procedure:

AddNewCustomer 'C10','Chen','SF','A',2000

Note: Optional: Execute AddNewCustomer 'C10','Chen','SF','A',2000

On-the-Fly Execution of a quoted String

Create Procedure ShowTable(@tableName varchar(30))Asexec ('select * from ' + @tableName)Return

Procedure with Output ParametersCREATE PROCEDURE showCustomers (@ID char(5), @CustRating char(1) output, @CustCredit numeric output)

ASselect @custRating=rating,@CustCredit=creditfrom customerwhere cid = @ID;

RETURN

Calling a procedure with output parameters:

Declare @rating char(1),@credit numeric(7,2)Exec ShowCustomers 'C1',@rating output ,@credit output select @rating,@credit

Triggers

• A trigger is a stored procedure associated with an action on a table.

• DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view.

• DDL triggers execute in response to a variety of data definition language (DDL) events. These events primarily correspond to Transact-SQL CREATE, ALTER, and DROP statements.

• Logon triggers fire in response to the LOGON event that is raised when a user sessions is being established.

Special Tables: Deleted, Inserted

• SQL Server maintains two temporary tables, Deleted and Inserted, to keep the deleted records and inserted records created by the last command.

• A modification is treated as a deletion of the old record, followed by an insertion of the new record. So the old record will be kept in the Deleted and the new record will be kept in the Inserted.

Create Trigger Command

CREATE TRIGGER trigger_name

ON tablename

AFTER { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }

AS

Example

Alter TRIGGER newCustomerTrigger ON Customer AFTER INSERTAS BEGIN

Select * from insertedPrint 'NewCustomerTrigger was fired'

ENDGO

ExampleCreate TRIGGER UpdateTrigger ON Customer AFTER UPDATEAS BEGIN

Select 'old record'select * from deletedSelect 'New record'select * from insertedif Update(Credit)

Beginrollback transactionSelect 'old record'select * from deletedselect 'New record'select * from inserted

ENDEnd

Note: Update(fieldName) tests if the field is updated

Using Inserted and Deleted Tables to Get the Old and New Values

CREATE TRIGGER showOldNewValues ON Customer AFTER UPDATEAS BEGIN

If Update(Credit)Beginselect d.cid,d.cname,d.credit as OldCredit,i.credit as NewCredit

from deleted d, inserted iwhere d.cid=i.cid

EndENDGO

Function Example

Create FUNCTION CreditEvaluation(@Credit numeric(7,2)) RETURNS char(5)ASBEGIN

declare @result char(5)if @Credit > 6000 select @result = 'Good'else select @result='Bad'return(@result)

END

To use the function:

select cid,cname,dbo.CreditEvaluation(credit)from customer