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.

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

Chapter 8 Embedded SQL.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
Chapter 4B: More Advanced PL/SQL Programming
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
ASP.NET Programming with C# and SQL Server First Edition Chapter 8 Manipulating SQL Server Databases with ASP.NET.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
SEMESTER 1, 2013/2014 DB2 APPLICATION DEVELOPMENT OVERVIEW.
SQL Basics. SQL SQL (Structured Query Language) is a special-purpose programming language designed from managing data in relational database management.
8 Copyright © 2004, Oracle. All rights reserved. Creating LOVs and Editors.
A Guide to SQL, Eighth Edition Chapter Three Creating Tables.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
CPS120: Introduction to Computer Science Information Systems: Database Management Nell Dale John Lewis.
4-1 INTERNET DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
SQL/lesson 2/Slide 1 of 45 Retrieving Result Sets Objectives In this lesson, you will learn to: * Use wildcards * Use the IS NULL and IS NOT NULL keywords.
Stored Procedures A stored procedure is a named collection of SQL statements language. You can create stored procedures for commonly used functions and.
Chapter 7 Advanced SQL Database Systems: Design, Implementation, and Management, Sixth Edition, Rob and Coronel.
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:14 Simple Queries in SQL Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
T-SQL Transact-SQL is microsoft implementation of SQL. It contains additional programming constracts T-SQL enables you to write programs that contain SQL.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
15/10/20151 PHP & MySQL 'Slide materials are based on W3Schools PHP tutorial, 'PHP website 'MySQL website.
PHP MySQL Introduction. MySQL is the most popular open-source database system. What is MySQL? MySQL is a database. The data in MySQL is stored in database.
SYST Web Technologies SYST Web Technologies Databases & MySQL.
CPS120: Introduction to Computer Science Lecture 19 Introduction to SQL.
Structure Query Language SQL. Database Terminology Employee ID 3 3 Last name Small First name Tony 5 5 Smith James
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 © Curt Hill Stored Procedures In Transact-SQL.
Stored Procedures Week 9. Test Details Stored Procedures SQL can call code written in iSeries High Level Languages –Called stored procedures SQL has.
Christopher M. Pascucci.NET Programming: Databases & ADO.NET.
1 CursorsCursors. 2 SQL Cursor A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
Manipulating Data in PL/SQL. 2 home back first prev next last What Will I Learn? Construct and execute PL/SQL statements that manipulate data with DML.
SQL Unit – 2 Base Knowledge Presented By Mr. R.Aravindhan.
SQL Basic. What is SQL? SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate with a database.
SQL Jan 20,2014. DBMS Stores data as records, tables etc. Accepts data and stores that data for later use Uses query languages for searching, sorting,
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
ITEC 224 Database Programming PL/SQL Lab Cursors.
Dr Gordon Russell, Napier University Unit Embedde SQL - V2.0 1 Embedded SQL Unit 5.1.
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
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.
G. Green 1.  Options include:  Script Files  already covered  APIs  last course topic  Database-Stored Code  our focus 2.
implicit and an explicit cursor
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.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
1 Stored Procedures in MySQL Part I. 2 Objectives SQL Vs. MySQL SP MySQL SP Parameters MySQL SP Control Structures.
DML Statements contd.. SQL Server CURSORS Cursor is used in handling results of select query for data calculations Cursors are used as buffered.
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
Unit-8 Introduction Of MySql. Types of table in PHP MySQL supports various of table types or storage engines to allow you to optimize your database. The.
Module 9: Using Advanced Techniques. Considerations for Querying Data Working with Data Types Cursors and Set-Based Queries Dynamic SQL Maintaining Query.
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.
Dynamic SQL Writing Efficient Queries on the Fly ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER.
Lec-7. The IN Operator The IN operator allows you to specify multiple values in a WHERE clause. SQL IN Syntax SELECT column_name(s) FROM table_name WHERE.
 MySQL is a database system used on the web  MySQL is a database system that runs on a server  MySQL is ideal for both small and large applications.
ASP.NET Programming with C# and SQL Server First Edition
Web Systems & Technologies
COMP 430 Intro. to Database Systems
A Guide to SQL, Seventh Edition
Task oriented processing
Dynamic SQL Writing Efficient Queries on the Fly
Dynamic SQL Writing Efficient Queries on the Fly
Introduction To Structured Query Language (SQL)
Introduction To Structured Query Language (SQL)
Presentation transcript:

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 be done quite simply from the application perspective where the statement is built on the fly whether you are using ASP.NET or any other programming language. But how do you do this from within a SQL Server stored procedure?

Dinamic SQL Dynamic SQL is a term used to mean SQL code that is generated programatically (in part or fully) by your program before it is executed. As a result it is a very flexable and powerful tool. You can use dynamic SQL to accomplish tasks such as adding where clauses to a search based on what fields are filled out on a form or to create tables with varying names.

How To Run Dinamic SQL SQL Server offers a few ways of running a dynamically built SQL statement. These ways are: Writing a query with parameters Using EXEC Using sp_executesql

Parameters - EXEC – SP_EXECUTESQL varchar(75) = 'London' SELECT * FROM customers WHERE City varchar(1000) varchar(75) varchar(75) = 'CustomerID, ContactName, City' = '''London''' = 'SELECT ' + ' FROM customers WHERE City = ' EXEC nvarchar(1000) varchar(75) varchar(75) = 'CustomerID, ContactName, City' = 'London' = 'SELECT ' + ' FROM customers WHERE City EXECUTE

Dinamic SQL in a Stored Procedure Create Procedure VarChar(100) AS SELECT * Create Procedure VarChar(100) AS VarChar(1000) = 'SELECT * FROM ' EXEC Create Procedure VarChar(100) AS VarChar(1000) = 'SELECT * FROM ' EXEC

SP_EXECUTESQL The system stored procedure sp_executesql behaves very similar to the EXECUTE command, however, it offers two advantages: 1.Parameters can stay in their native data type - with EXECUTE you will have to pass a string; therefore, everything needs to be converted to string data types with EXEC. 2.Query optimizer is more likely to re-use the existing execution plans if you have to run the same query with different parameters. The reason for this is that the text of the query does not change with sp_executesql - with EXEC you pass a different string each time.

SP_EXECUTESQL sp_executesql itionList], The parameters are specified with a name and type. We can specify the parameters for both input and output.

Dinamic SQL Samples (1) CREATE PROCEDURE GENERAL_SELECT varchar(75)) AS BEGIN NVARCHAR(200) = 'SELECT ' + ' FROM ‘ EXECUTE END

Dinamic SQL Samples (2) CREATE PROCEDURE usp_GetNumberOfRecord INT OUTPUT ) AS BEGIN NVARCHAR(2000) NVARCHAR(4000) NVARCHAR(500) = INT OUTPUT' = = COUNT(*)+1 FROM ' @TotalRowsReturned OUTPUT END

Dinamic SQL Samples (3) INT = ‘Customers' EXECUTE = OUTPUT as NextRow

Cursor Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time. There are times when you want to loop through a series of rows a perform processing for each row. The should only be used when you truly need to access one row at a time. The only reason for that is to call a stored procedure on each row For example, you can use cursor to include a list of all user databases and make multiple operations against each database by passing each database name as a variable.

Cursor Life Cycle A cursor life cycle can be described as follows: 1.Cursor is declared using the DECLARE CURSOR statement. This statement creates a cursor within SQL Server memory 2.Cursor is activated using OPEN CURSOR statement. At this point you can populate the cursor with a record set. 3.Data is retrieved from the cursor using the FETCH keyword. 4.A WHILE loop is executed within the cursor to perform some operation with the rows in the cursor with the condition that the FETCH command is successful. 5.Cursor is deactivated using CLOSE CURSOR statement. At this point you can't populate the cursor with additional rows. Nor can you work w ith rows within the cursor. However, you can re-open the cursor with OPEN CURSOR statement and perform additional work with the cursor. 6.The cursor is destroyed using DEALLOCATE CURSOR statement. Once the cursor is de-allocated it cannot be reopened.

Cursor Syntax DECLARE cursor_name [INSENSITIVE] [SCROLL] CURSOR FOR select_statement [FOR {READ ONLY | UPDATE [OF column_name [,...n]]}] OPEN { { [GLOBAL] cursor_name } | cursor_variable_name} FETCH [[ NEXT | PRIOR | FIRST | LAST | ABSOLUTE {n | RELATIVE {n ] FROM ] { { [GLOBAL] cursor_name } ] CLOSE { {[GLOBAL] cursor_name } | cursor_variable_name } DEALLOCATE { { [GLOBAL] cursor_ name }

Cursor Samples nvarchar(40) int CURSOR = CURSOR FOR SELECT ProductName FROM Products FETCH NEXT WHILE = 0 BEGIN PRINT 'Product #' + AS char(3)) SET FETCH NEXT END

Cursor Functions CURSOR_STATUS

valueMeaning 0Successful fetch of a row within a cursor Fetch has failed. This could mean that the cursor has reached the beginning (or end) of the record set. This could also mean that we attempted retrieving a record that does not exist. For instance, if you attempt to grab 51st record within a cursor that has 50 records fetch status will be The fetched row is missing. This means the record you're trying to FETCH has been deleted or its key has been updated since you have opened the cursor. The most commonly used cursor function is This function determines whether FETCH keyword has successfully retrieved a row from the current cursor. can take one of the three values:

Example VARCHAR(85) DECLARE employee_cursor CURSOR FOR SELECT TOP 5 FirstName + ' ' + LastName + ' ' + Title FROM Employees OPEN employee_cursor FETCH NEXT FROM employee_cursor WHILE = 0 BEGIN FETCH NEXT FROM employee_cursor SELECT AS fetch_status END CLOSE employee_cursor DEALLOCATE employee_cursor

function returns the number of rows in the cursor which was opened last on the current connection. This means that if you have 3 cursors open will return the number of rows in the 3rd cursor. can take the following values: valueMeaning -m Cursor is being populated asynchronously. "M" is the value of records in the record set. The cursor is DYNAMIC; that means, it reflects the changes to the data within the cursor. Therefore the number of rows can change due to addition or deletion of rows in the underlying tables. DYNAMIC cursors always return -1 as value of 0 This can mean one of the following: Cursor has not been opened Cursor has no rows Cursor has been closed N Number of rows in the cursor record set. N is reported after the cursor has been fully populated

Example VARCHAR(20) DECLARE MY_CURSOR CURSOR FOR SELECT TOP 3 LASTNAME, FIRSTNAME FROM EMPLOYEES SELECT 'cursor has ' + AS VARCHAR) + ' rows' OPEN MY_CURSOR FETCH NEXT FROM SELECT 'cursor has ' + AS VARCHAR) + ' rows' WHILE = 0 BEGIN FETCH NEXT FROM END CLOSE MY_CURSOR SELECT 'cursor has ' + AS VARCHAR) + ' rows' DEALLOCATE MY_CURSOR

CURSOR_STATUS The CURSOR_STATUS function can be used effectively within a stored procedure that calls another stored procedure. Which returns an output parameter of CURSOR data type. This function can be used with local or global cursors and determines whether or not the stored procedure has returned a cursor with a result set. CURSOR_STATUS( 'local' or 'global', cursor name) CURSOR_STATUS ('variable', cursor variable name)

The values returned by CURSOR_STATUS function CURSOR_ STATUS value Meaning for variableMeaning for cursor name 1 Cursor is open and has at least 1 row DYNAMIC cursors return 1 even if they contain no rows Cursor is open and has at least 1 row DYNAMIC cursors return 1 even if they contain no rows 0Cursor is open but has no rowsCursor has no rows The cursor is closed -2 Cursor wasn't returned by the called procedure OR the cursor was deallocated prior to being assigned to this variable The value of 2 is never returned by CURSOR_STATUS if you refer to cursor name -3 Cursor variable with the specified name does not exist OR the variable exists, but it hasn't been assigned to a cursor returned from the called procedure Cursor with the specified name does not exist

CURSOR_STATUS Example (1) CREATE PROCEDURE CURSOR VARYING OUTPUT) AS BEGIN SET NOCOUNT ON = CURSOR STATIC FOR SELECT LastName, FirstName FROM Employees WHERE LastName END

CURSOR_STATUS Example (2) CREATE PROCEDURE VARCHAR(50) AS SET NOCOUNT ON VARCHAR(20) CURSOR EXECUTE RETURN_EMPLOYEE_NAMES OUTPUT IF = 0 BEGIN PRINT 'no records found' RETURN END ELSE BEGIN FETCH NEXT INTO WHILE = 0 FETCH NEXT INTO END END

CURSOR_STATUS Example (3) EXECUTE call_the_other_procedure 'king'

Daftar Pustaka mic-sql-commands-in-sql-server/ sor_Functions