T-SQL Transact-SQL is microsoft implementation of SQL. It contains additional programming constracts T-SQL enables you to write programs that contain SQL.

Slides:



Advertisements
Similar presentations
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Advertisements

What Is a User-defined Function? Scalar Functions –Similar to a built-in function Multi-Statement Table-valued Functions –Content like a stored procedure.
Session 2 Access to SQL Server 2000 Adam Cogan Database Architect ssw.com.au.
Instructor: Craig Duckett CASE, ORDER BY, GROUP BY, HAVING, Subqueries
Chapter 4B: More Advanced PL/SQL Programming
Stored Procedures and Functions Rose-Hulman Institute of Technology Curt Clifton.
Module 10: Implementing User-defined Functions. Overview What Is a User-defined Function? Defining Examples.
Tools of the trade TSQL CIS 407. SQL Server Tools Books on line! Don’t use sql server authentication –Use windows authentication (safer) for developer.
Introduction to PL/SQL
Topics Views Stored Procedures User Defined Functions Triggers.
2015 International TechNet Wiki Summit 2015 Saeid Hasani Structured Error Handling Mechanism in SQL Server 2012 & 2014.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Module 12 Handling Errors in T-SQL Code. Module Overview Understanding T-SQL Error Handling Implementing T-SQL Error Handling Implementing Structured.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
Functions Lesson 10. Skills Matrix Function A function is a piece of code or routine that accepts parameters and stored as an object in SQL Server. The.
Introduction to Databases Chapter 7: Data Access and Manipulation.
Dinamic SQL & Cursor. Why Dinamic SQL ? Sometimes there is a need to dynamically create a SQL statement on the fly and then run that command. This can.
Stored Procedures, Transactions, and Error-Handling
Module 8: Implementing Stored Procedures. Introducing Stored Procedures Creating, Modifying, Dropping, and Executing Stored Procedures Using Parameters.
Module 1: Introduction to Transact-SQL
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 7 PL/SQL Packages.
1 Definition of a subquery Nested subqueries Correlated subqueries The ISNULL function Derived tables The EXISTS operator Mixing data types: CAST & CONVERT.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
5/24/01 Leveraging SQL Server 2000 in ColdFusion Applications December 9, 2003 Chris Lomvardias SRA International
PL/SQL vs. Transact-SQL. Transact-SQL Central to the use of Microsoft® SQL Server™. All applications that communicate with SQL Server do so by sending.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
IMS 4212: Intro to SQL 1 Dr. Lawrence West, Management Dept., University of Central Florida Introduction to SQL—Topics Introduction to.
Upgrading to SQL Server 2000 Kashef Mughal. Multiple Versions SQL Server 2000 supports multiple versions of SQL Server on the same machine It does that.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
SQL Server. اسکریپت درج مقدار در جدول USE Accounting; int; INSERT INTO Orders (CustomerNo,OrderDate, EmployeeID) VALUES (gETDATE,1); SELECT.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
10 | Programming with Transact-SQL Graeme Malcolm | Senior Content Developer, Microsoft Geoff Allix | Principal Technologist, Content Master.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
06 | Modifying Data in SQL Server Brian Alderman | MCT, CEO / Founder of MicroTechPoint Tobias Ternstrom | Microsoft SQL Server Program Manager.
Slide 1 of 19Session 13 Ver. 1.0 Querying and Managing Data Using SQL Server 2005 In this session, you will learn to: Implement stored procedures Implement.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
G. Green 1.  Options include:  Script Files  already covered  APIs  last course topic  Database-Stored Code  our focus 2.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
Copyright © 2013 Curt Hill Triggers The Generation of Indirect Actions.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
IMS 4212: Constraints & Triggers 1 Dr. Lawrence West, Management Dept., University of Central Florida Stored Procedures in SQL Server.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Module 9: Using Advanced Techniques. Considerations for Querying Data Working with Data Types Cursors and Set-Based Queries Dynamic SQL Maintaining Query.
SQL Triggers, Functions & Stored Procedures Programming Operations.
1 Stored Procedure, Function and Trigger. 2Objectives 1. Database Programming 2. Stored Procedure 3. Function 4. Trigger.
In this session, you will learn to: Create and manage views Implement a full-text search Implement batches Objectives.
Module 9: Implementing Functions. Overview Creating and Using Functions Working with Functions Controlling Execution Context.
Module 9: Implementing User-Defined Functions. Overview Introducing User-Defined Functions Implementing User-Defined Functions.
Implementing Functions Advanced Database Dr. AlaaEddin Almabhouh.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Oracle9i Developer: PL/SQL Programming Chapter 6 PL/SQL Packages.
COMP 430 Intro. to Database Systems
MySQL Subquery Source: Dev.MySql.com
Instructor: Craig Duckett Lecture 09: Tuesday, April 25th, 2017
11 | Error Handling and Transactions
10 | Programming with Transact-SQL
Programmability by Adrienne Watt.
PROCEDURES, CONDITIONAL LOGIC, EXCEPTION HANDLING, TRIGGERS
Error Handling Summary of the next few pages: Error Handling Cursors.
Chapter 8 Advanced SQL.
Database Systems: Design, Implementation, and Management Tenth Edition
T-SQL Transact-SQL is microsoft implementation of SQL.
Presentation transcript:

T-SQL Transact-SQL is microsoft implementation of SQL. It contains additional programming constracts T-SQL enables you to write programs that contain SQL statements.

Using Variables You can declare variable using DECLARE statement, followed by the variable name and the type type For example nvarchar(40) int

Using Variables Variables are initially set to null. You set a variables’ value using SET statement ‘Chai’ = 7 The following SELECT statement uses these variables: Select ProductId, ProductName, UnitPrice From Products Where OR

Using Conditional Logic T-SQL enables you to use conditional logic operaters in SQL stataments. IF-then-ELSE IF conditon statement 1 ELSE statement 2 You can replace a single statement with multiple statements by placing those statements within BEGIN and END statements

Using Conditional Logic If (Select Count(*) from products where unitprice 0 BEGIN Print ‘The following products have a UnitPrice of less than 5’ Select ProductId, ProductName, UnitPrice From Products Where UnitPrice<5 END Else BEGIN Print ‘There are no products that have a UnitPrice of less than 5’ END

Using CASE Statement The following example uses a select statement to retrieve the value Massachusetts returned by the case statement: nchar(2) =‘MA’ nvarchar(15) Select as State When ‘CA’ then ‘California’ When ‘MA’ then ‘Massachusetts’ When ‘NY’ then ‘New York’ End

Using CASE Statement You can store the value retrived by the SELECT statement in a variable as shown in the example nchar(2) =‘MA’ nvarchar(15) When ‘CA’ then ‘California’ When ‘MA’ then ‘Massachusetts’ When ‘NY’ then ‘New York’ End

Using CASE Statement You can also compare a column value in a CASE statement Select Price= Case When UnitPrice is NULL then 'Unknown' When UnitPrice <10 then 'Less than 10' When UnitPrice =10 then '10' Else 'Greater than 10' End From Products

While Loops While conditon statement The following example shows a while loop: int = 5 While Begin Print ‘count=’ + Set End

Continue Statement You can use the Continue statement to start a next iteration of while loop immediately, skipping over any remaining code in the loop. int = 5 While Begin Print ‘count=’ + Set if Begin Set Continue end End

Break Statement int = 5 While Begin Print ‘count=’ + Set If Begin Break End

Using Labels and the Goto Statement You use the Goto statement to jump a specified label in your code; you use a label to identify a statement of your code. int = 5 myLabel: Print ‘count=’ + Set If Begin GOTO myLabel End Output of these code is the same with the while loop’s output

Using Waitfor Statement There are times when you want your program to pause before running some code to perform a specific action, such as running a batch program at night to update customer records WAITFOR {DELAY ‘ time interval’ | TIME ‘actual time’} Waitfor Delay ‘00:00:05’ waits for a time interval of 5 seconds

Using Waitfor Statement Using WAITFOR TIME: The following example executes the stored procedure sp_update_job at 10:20 P.M. (22:20). USE msdb; EXECUTE = 'TestJob'; BEGIN WAITFOR TIME '22:20'; EXECUTE = = 'UpdatedJob'; END; GO

Using Waitfor Statement Using WAITFOR DELAY: The following example executes the stored procedure after a two-hour delay. BEGIN WAITFOR DELAY '02:00'; EXECUTE sp_helpdb; END; GO

Using Raiserror Statement You use the Raiserror statement to generate an error message. It is typically used to if an error is occurs in one of your stored procedures. Syntax: RAISERROR({number | description}{, severity, state}) Number is error number and between 50,001 and 2,147,483,648 Description is the error message Severity is the degree of the error and between 0 and 18

Using Raiserror Statement The following code example shows how to use RAISERROR inside a TRY block to cause execution to jump to the associated CATCH block. It also shows how to use RAISERROR to return information about the error that invoked the CATCH block. BEGIN TRY -- RAISERROR with severity will cause execution to -- jump to the CATCH block. RAISERROR ('Error raised in TRY block.', -- Message text. 16, -- Severity State. ); END TRY BEGIN CATCH NVARCHAR(4000); INT; INT; = = = ERROR_STATE(); -- Use RAISERROR inside the CATCH block to return error -- information about the original error that caused -- execution to jump to the CATCH block. RAISERROR -- Message State. ); END CATCH;

Using Cursor When you execute a SELECT statement, all the effected rows are returned in one go. Sometimes you might want to take some action based on the column values retrived for a particular row. To do this, you can use a cursor to process rows retrived from the database one row at a time.

Using Cursor You follow these steps when using a cursor: Declare Variables to Store the Column Values from the Select Statement These variables must be compatible with the column types for the retrieved rows. Example: int nvarchar (40) money

Using Cursor Declare the Cursor A cursor declaration consists of a name that you assign to the cursor and a SELECT statement that you want to execute retrieved rows. This SELECT statement is not actually run until you open the cursor. Example: DECLARE ProductCursor CURSOR for Select ProductID, ProductName, UnitPrice from Products Where ProductID<=10

Using Cursor Open the Cursor You open a cursor using the OPEN statement. OPEN ProductCursor Fetch the Rows from the Cursor To read each row from your cursor, use the fetch statement Since there might be many rows, you need to usee While loop. To check end of loop, use function. This function returns: 0 if FETCH statement successfully returned a row. -1if FETCH statement failed or the requested row is outside the result set. -2 if Row fetched is missing

Using Cursor The following example shows a loop that reads each row from ProductCursor. Fetch Next from @MyUnitPrice Print + Convert Print + Convert Print + Convert While Begin Fetch Next from @MyUnitPrice Print + Convert Print + Convert Print + Convert END

Using Cursor Close the Cursor You close a cursor using the CLOSE statement. CLOSE ProductCursor You should also remoce the reference to your curs or using the DEALLOCATE statement. DEALLOCATE ProductCursor

Functions There are many built-in functions to use in T- SQL. You can find detailed explanation about these functions from the web site below: us/library/ms aspx

Creating User-Defined Functions You create a function using the CREATE FUNCTION statement. There are three types of user-defined functions: Scalar Functions: These functions returns a single value. Inline Table-valued Functions: Returns an object of the table type. You can think of a table a a regular database table, except it is stored in memory. An inline table-valued function can return the results retrived by only a single SELECT statement. Multistatement table-valued Function: Returns a object of table type and it can contain multiple T- SQL statement.

Creating User-Defined Functions Scalar Functions: The example below creates the DiscountPrice() function, which returns the original price of an item multipled by a discount factor. Create Function money) Returns Money As Begin End Using this function: Float =0.3 Select ), UnitPrice From Products Where ProductID=1

Creating User-Defined Functions Inline Table-Valued Functions: Inline user- defined functions are a subset of user-defined functions that return a table. Inline functions can be used to achieve the functionality of parameterized views. Consider this view: CREATE VIEW vw_CustomerNamesInWA AS SELECT CustomerID, CompanyName FROM Northwind.dbo.Customers WHERE Region = 'WA'

Creating User-Defined Functions Inline Table-Valued Functions: You can create a more generalized version, vw_CustomerNamesInRegion, by replacing the WHERE Region = 'WA' with a WHERE Region and letting users specify the region they are interested in viewing. Views, however, do not support parameters in the search conditions specified in the WHERE clause.

Creating User-Defined Functions CREATE FUNCTION fn_CustomerNamesInRegion nvarchar(30) ) RETURNS table AS RETURN ( SELECT CustomerID, CompanyName FROM Northwind.dbo.Customers WHERE Region ) -- Example of calling the function for a specific region SELECT * FROM fn_CustomerNamesInRegion(N'WA')

Creating User-Defined Functions Inline user-defined functions follow these rules: The RETURNS clause contains only the keyword table. You do not have to define the format of a return variable because it is set by the format of the result set of the SELECT statement in the RETURN clause. There is no function_body delimited by BEGIN and END. The RETURN clause contains a single SELECT statement in parentheses. The result set of the SELECT statement forms the table returned by the function. The SELECT statement used in an inline function is subject to the same restrictions as SELECT statements used in views. The table-valued function accepts only constants arguments

Creating User-Defined Functions Inline Table-Valued Functions: The example below creates the ProductsToBeReordered() function, which returns a table containing the rows from the Products table Create Function ProductsToBeReordered int) Returns Table As Return ( Select * From Products Where ) Using this function: Select ProductID, ProductName, UnitsInStock From ProductsToBeReordered(10) Where ProductId<=50;

Creating User-Defined Functions Multistatement Table-Valued Functions: User-defined functions that return a table can be powerful alternatives to views. A user-defined function that returns a table can be used where table or view expressions are allowed in Transact-SQL queries. While views are limited to a single SELECT statement, user-defined functions can contain additional statements that allow more powerful logic than is possible in views. In a user-defined function that returns a table: The RETURNS clause defines a local return variable name for the table returned by the function. The RETURNS clause also defines the format of the table. The scope of the local return variable name is local within the function. The Transact-SQL statements in the function body build and insert rows into the return variable defined by the RETURNS clause. When a RETURN statement is executed, the rows inserted into the variable are returned as the tabular output of the function. The RETURN statement cannot have an argument.

Creating User-Defined Functions This example creates a function in the Northwind database that returns a table: CREATE FUNCTION LargeOrderShippers money ) TABLE ( ShipperID int, ShipperName nvarchar(80), OrderID int, ShippedDate datetime, Freight money ) AS BEGIN SELECT S.ShipperID, S.CompanyName, O.OrderID, O.ShippedDate, O.Freight FROM Shippers AS S INNER JOIN Orders AS O ON S.ShipperID = O.ShipVia WHERE O.Freight RETURN END This query references the table returned by the function in its FROM clause: SELECT * FROM LargeOrderShippers( $500 )

Creating User-Defined Functions Multistatement Table-Valued Functions: The example below creates the ProductsToBeReordered2() function, which returns a table containing the rows from the Products table Create Function ProductsToBeReordered2 int) table ( ProductID int, ProductName nvarchar(40), UnitsInStock smallint, Reorder nvarchar(3) ) As Begin Insert Select ProductID, ProductName, UnitsInStock, ‘no’ from Products Set Reorder=‘yes’ Where Return End Usage of the function Select * from ProductsToBeReordered2(20)