Copyright © 2012-2013 - Curt Hill Stored Procedures In Transact-SQL.

Slides:



Advertisements
Similar presentations
PHP SQL. Connection code:- mysql_connect("server", "username", "password"); Connect to the Database Server with the authorised user and password. Eg $connect.
Advertisements

Transact-SQL. 1. Declare float = 10 select * from customers where discnt
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Fundamentals, Design, and Implementation, 9/e Chapter 12 ODBC, OLE DB, ADO, and ASP.
Fundamentals, Design, and Implementation, 9/e COS 346 DAY 22.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
1 Nassau Community CollegeProf. Vincent Costa Acknowledgements: Introduction to Database Management, All Rights ReservedIntroduction to Database Management.
Introduction To Databases IDIA 618 Fall 2014 Bridget M. Blodgett.
Module 2: Using Transact-SQL Querying Tools. Overview SQL Query Analyzer Using the Object Browser Tool in SQL Query Analyzer Using Templates in SQL Query.
Copyright © Curt Hill SQL The Data Definition Language.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
MySQL in PHP – Page 1 of 17CSCI 2910 – Client/Server-Side Programming CSCI 2910 Client/Server-Side Programming Topic: MySQL in PHP Reading: Williams &
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
Copyright © 2003 Pearson Education, Inc. Slide 8-1 The Web Wizard’s Guide to PHP by David Lash.
Stored Procedures A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and.
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
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.
Dexterity | CONFIDENTIAL 2009 MRO | Analytics | Insights 1 Stored Procedures.
TRAINING SESSIONS SQL Server Basics Design By.:.Net Prepared By:Dilip Namdeo Dated:23-Dec-09 Reference Site:
Stored Procedures, Transactions, and Error-Handling
Chapter 6 PHP Interacts with Mysql Database. Introduction In PHP, there is no consolidated interface. Instead, a set of library functions are provided.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
PL/SQLPL/SQL Oracle11g : PL/SQL Programming Chapter 6 Functions.
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.
Copyright © 2013 Curt Hill Database Security An Overview with some SQL.
Copyright © Curt Hill SQL The Intergalactic Standard Database Query Language.
Advanced SQL: Cursors & Stored Procedures
Oracle 11g DATABASE DEVELOPMENT LAB1. Introduction  Oracle 11g Database:-  Oracle 11g database is designed for some features, which helps to the organizations.
Stored Procedure. Objective At the end of the session you will be able to know :  What are Stored Procedures?  Create a Stored Procedure  Execute a.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
3-Tier Client/Server Internet Example. TIER 1 - User interface and navigation Labeled Tier 1 in the following graphic, this layer comprises the entire.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 8 Advanced SQL.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
Copyright © Curt Hill Joins Revisited What is there beyond Natural Joins?
Dr Gordon Russell, Napier University Unit Embedde SQL - V2.0 1 Embedded SQL Unit 5.1.
Dynamic SQL. 2 home back first prev next last What Will I Learn? Recall the stages through which all SQL statements pass Describe the reasons for using.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Transact SQL The language of Microsoft SQLServer Copyright © 2012 – 2014 by Curt Hill.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Parser Generation Using SLK and Flex++ Copyright © 2015 Curt Hill.
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
Copyright © 2013 Curt Hill Triggers The Generation of Indirect Actions.
Stored Procedures / Session 4/ 1 of 41 Session 4 Module 7: Introducing stored procedures Module 8: More about stored procedures.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Web Database Programming Using PHP.
IMS 4212: Application Architecture and Intro to Stored Procedures 1 Dr. Lawrence West, Management Dept., University of Central Florida
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
IT420: Database Management and Organization Triggers and Stored Procedures 24 February 2006 Adina Crăiniceanu
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
ADVANCED SQL.  The SQL ORDER BY Keyword  The ORDER BY keyword is used to sort the result-set by one or more columns.  The ORDER BY keyword sorts the.
Copyright © Curt Hill SQL The Data Manipulation Language.
Dynamic SQL Writing Efficient Queries on the Fly ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
1 c6212 Advanced Database and Client Server MS SQL Server 2000 Stored Procedures and Parameters What ? Why ? How ?
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
Dynamic SQL Writing Efficient Queries on the Fly
Views, Stored Procedures, Functions, and Triggers
UNIT - V STORED PROCEDURE.
Database Application Development
Error Handling Summary of the next few pages: Error Handling Cursors.
MATLAB: Structures and File I/O
Stored Procedure used in PosgreSQL
Procedures Organized by Farrokh Alemi, Ph.D. Narrated by Yara Alemi
Using SQL*Plus.
Copyright © 2013 – 2018 by Curt Hill
Information Management
Database Application Development
Presentation transcript:

Copyright © Curt Hill Stored Procedures In Transact-SQL

Introduction In a previous presentation we examined the programming features of SQL Server’s extensions to SQL What we did not cover are Procedures or Functions –Important aspects of real programming Today we fix that First, how to executed Second, a sampling of predefined stored procedures Third, how to define Copyright © Curt Hill

Executing a procedure A stored procedure is started by the Execute statement –Which may be abbreviated to Exec The format is: EXEC[UTE] = ] spname [ parms ] –Where –Spname is the name of procedure –The return value is optional and placed in a previously declared variable –The parameters vary per procedure Copyright © Curt Hill

Notes The parameters may be defined by name or positionally To define by name = value The values passed to a stored procedure may be constants, variables or table values Next we will survey a few predefined stored procedures and then look at some example calls Copyright © Curt Hill

Some predefined Predefined stored procedures have a common naming convention –Always starts with sp_ or xp_ There are more than 350 predefined ones –Just a few of these will be examined Copyright © Curt Hill

List 1 sp_add_job – adds a batch job to the system See also sp_add_jobstep and sp_add_jobschedule, sp_update_job, etc. sp_addlogin – add a login name and password sp_addmessage – add an error message to system error message table sp_catalogs – displays catalog listing Copyright © Curt Hill

List 2 sp_columns – display catalog info for tables or views sp_databases – display the databases on this server sp_executesql – execute a statement within a string sp_help – display help – many others such as sp_helpindex sp_indexes – display index information Copyright © Curt Hill

List 3 sp_lock – displays information in locks sp_monitor – displays information on resources sp_password – update the password for a login sp_primarykeys – duh sp_rename sp_tables Copyright © Curt Hill

Execute examples Copyright © Curt Hill

The other prefix There are a series of stored procedures that start with xp_ These are typically system commands, rather than database commands An example is: xp_cmdshell ‘cmd’ The cmd is passed to windows to be executed Copyright © Curt Hill

Defining our own We may also define our own stored procedures A stored procedure is just that: Transact SQL code that is stored on the server It may then be used just like a predefined The Create Procedure command creates and stores it on the server Copyright © Curt Hill

Create Procedure Form: CREATE PROC[EDURE] procedure_name [;number] parms as statements Where –Procedure_name is the name –Number is optional and creates a group of procedures –Parms is discussed next –Statements are the body of the procedure Copyright © Curt Hill

Parameters There are zero or more parameters The type [VARYING] [= value] [OUTPUT] The name is first, followed by the type Varying is only used if this is a cursor type Output means that the parameter is a reference type The = gives a default value Copyright © Curt Hill

Notes The parameter must follow the normal naming convention –Start if normal variable –Start with letter if cursor Cursors must use varying and output Copyright © Curt Hill

Connection Stored procedures belong to a particular database Therefore the use is almost always required However, Create Procedure must be the first command in a batch Thus separate with a GO Copyright © Curt Hill

Example 1 A stored procedure that does a simple query: Create Procedure MyProc AS Select f_name, f_naid From faculty Where f_age > 40 Stored procedures are precompiled, so executing this is faster than the normal query Copyright © Curt Hill

Return value A stored procedure may return an integer only It does this with the return statement The form of the execute then becomes: = Proc parms Copyright © Curt Hill

Count Rows Here is an example that will count rows in this query –This could be done easily with an aggregate function but this is a nice example There are two pieces –The stored procedure –The use of it Copyright © Curt Hill

Counter Definition Copyright © Curt Hill use college go Create Proc Counter as return varchar(20) = 0 declare curses Cursor for select f_name from faculty where f_age > 40 open curses fetch next from curses while >= 0) begin + 1 fetch next from curses end deallocate

Counter Use Copyright © Curt Hill use college int = -11 = Counter Results in no table output but only this in messages 14

Output values If the procedure needs to produce something other than one integer, then reference parameters are needed These have OUTPUT as a suffix on the parameter declaration They also need these in the actual parameter list What does this tell us about Microsoft designed languages? Copyright © Curt Hill

Last Example Lets find the highest and lowest ratios again The stored procedure is simliar to the version in the Transact SQL presentation Only the prefix is different Copyright © Curt Hill

High Low Defined Copyright © Curt Hill use college go create proc real varchar(20) real varchar(20) output as declare fac_curse cursor for select f_name, f_age, f_years from faculty where f_age > 40 open fac_curse -- Rest is same

High Low Called Copyright © Curt Hill use college varchar(20) exec output print 'Lowest + ' ' + print 'Highest + ' ' +

Execute again The normal purpose of the Execute command is to start a stored procedure It has another use as well It may execute a string –Literal –Variable The string should be a query or other executable command Copyright © Curt Hill

Notes The string option allows us to pass a query or other command to a stored procedure This will mess with optimization Normally a stored procedure is precompiled –However it cannot precompile a command it has not received Copyright © Curt Hill

Other procedure commands We remove procedures with: DROP PROCEDURE proc_name This must be executed within the correct database We may also Alter the stored procedure Copyright © Curt Hill

Functions A function is a procedure that returns a value The syntax is similar: Create Function name type, … ) Returns type Begin body Return expression End Copyright © Curt Hill

There is More SQL Server has no monopoly on these things Oracle, MySQL, PostgreSQL, DB2 among others, have both procedures and functions There should be no surprise that –The capabilities are similar –The syntax is different Copyright © Curt Hill

Finally A stored procedure saves us work for frequently used code It is faster than the normal because it is precompiled It may also be used by anyone on the database Copyright © Curt Hill