Homework Assignment. 1. Stored Procedures (SPs)

Size: px
Start display at page:

Download "Homework Assignment. 1. Stored Procedures (SPs)"

Transcription

1 Homework Assignment In this homework, you will practice how to create database objects such as stored procedures, stored functions, triggers, and events. 1. Stored Procedures (SPs) Stored procedure is a piece of code (procedure) consisting of declarative and procedural SQL statements stored in the catalog of a database that can be activated by calling it from a program, a trigger, or another stored procedure. The following Figure shows how a stored procedure is processed. The left block represents the program from which the procedure is called, the middle block represents the database server, and the right side represents the database and its catalog. The process begins when the procedure is called from the program (step 1). The database server receives this call and finds the matching procedure in the catalog (step 2). Next, the procedure is executed (step 3). After execution, a code is returned indicating that the procedure was processed correctly (step 4). No communication takes place between the database server and the program during the execution of the procedure. Four types of stored programs Stored procedure: can be called from an application that has access to the database Stored function: can be called from SQL statement. A stored function works much like the MySQL built in functions Trigger: is executed in response to an INSERT, UPDATE, or DELETE statement on a specified table Event: is executed at a scheduled time Stored procedures and stored functions are often referred to as stored routines 1

2 Example: a script that creates and calls a stored procedure DROP PROCEDURE IF EXISTS test; -- Change statement delimiter from semicolon to double front slash CREATE PROCEDURE test() DECLARE sum_balance_due_var DECIMAL(9, 2); SELECT SUM(invoice_total - payment_total - credit_total) INTO sum_balance_due_var FROM invoices WHERE vendor_id = 95; -- for testing, the vendor with an ID of 37 has a balance due IF sum_balance_due_var > 0 THEN SELECT CONCAT('Balance due: $', sum_balance_due_var) AS message; ELSE SELECT 'Balance paid in full' AS message; -- Change statement delimiter from semicolon to double front slash CALL test(); The response from the system SQL statements for controlling the flow of execution MySQL provides statements that can be used within scripts to add functionality similar to that provided by procedural programming languages. he flow of execution based on a condition 2

3 REPEAT...UNTIL...END REPEAT //repeats statements while a condition is true DECLARE CURSOR FOR // defines a result set that can be processed by DECLARE...HANDLER //defines a handler that s executed when a stored program encounters an error A SQL statement used within stored programs SELECT: returns a result set to the calling program. Or retrieves data from the database and stores it so it can be processed by the stored program. Example: a stored procedure that displays a message DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() SELECT 'This is a test.' AS message; CALL test(); How to declare and set variables A variable stores a value that can change as the procedure executes. A variable must have a name that is different from the names of any columns used in any SELECT statement within the stored program. To distinguish a variable from a column, you can add a suffix like _var to the variable name. The syntax for declaring a variable DECLARE variable_name data_type [DEFAULT literal_value]; The syntax for setting a variable to a literal value or an expression SET variable_name = literal_value_or_expression; The syntax for setting a variable to a selected value SELECT column_1[, column_2]... INTO variable_name_1[, variable_name_2]... Example: A stored procedure that uses variables DROP PROCEDURE IF EXISTS test; 3

4 CREATE PROCEDURE test() DECLARE max_invoice_total DECIMAL(9,2); DECLARE min_invoice_total DECIMAL(9,2); DECLARE percent_difference DECIMAL(9,4); DECLARE count_invoice_id INT; DECLARE vendor_id_var INT; SET vendor_id_var = 95; SELECT MAX(invoice_total), MIN(invoice_total), COUNT(invoice_id) INTO max_invoice_total, min_invoice_total, count_invoice_id FROM invoices WHERE vendor_id = vendor_id_var; SET percent_difference = (max_invoice_total - min_invoice_total) / min_invoice_total * 100; SELECT CONCAT('$', max_invoice_total) AS 'Maximum invoice', CONCAT('$', min_invoice_total) AS 'Minimum invoice', CONCAT('%', ROUND(percent_difference, 2)) AS 'Percent difference', count_invoice_id AS 'Number of invoices'; CALL test(); The response from the system How to code the IF statements The syntax of the IF statement IF boolean_expression THEN statement_1; [statement_2;]... [ELSEIF boolean_expression THEN statement_1; [statement_2;]...]... [ELSE statement_1; [statement_2;]...] 4

5 You can nest an IF statement within another IF statement or within other SQL statements such as statements for coding loops. You can also code parentheses around the Boolean expressions in an IF statement. (e.g., IF(first_invoice_due_date < NOW()) THEN ) Example DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() DECLARE first_invoice_due_date DATE; SELECT MIN(invoice_due_date) INTO first_invoice_due_date FROM invoices WHERE invoice_total - payment_total - credit_total > 0; IF first_invoice_due_date < NOW() THEN SELECT 'Outstanding invoices overdue!'; ELSEIF first_invoice_due_date = SYSDATE() THEN SELECT 'Outstanding invoices are due today!'; ELSE SELECT 'No invoices are overdue.'; -- the IF statement rewritten as a Searched CASE statement /* CASE WHEN first_invoice_due_date < NOW() THEN SELECT 'Outstanding invoices overdue!' AS Message; WHEN first_invoice_due_date = NOW() THEN SELECT 'Outstanding invoices are due today!' AS Message; ELSE SELECT 'No invoices are overdue.' AS Message; END CASE; */ CALL test(); The response from the system 5

6 SELECT NOW(),CURDATE(),CURTIME(), SYSDATE(); CASE Statements The syntax of the simple CASE statement CASE expression WHEN expression_value_1 THEN statement_1; [statement_2;]... [WHEN expression_value_2 THEN statement_1; [statement_2;]...]... [ELSE statement_1; [statement_2;]...] END CASE; The syntax of the searched CASE statement CASE WHEN boolean_expression THEN statement_1; [statement_2;]... [WHEN boolean_expression THEN statement_1; [statement_2;]...]... [ELSE statement_1; [statement_2;]...] END CASE; You can use a simple CASE statement or a searched CASE statement to execute one or more statements depending on a value that s returned by an expression. Example: DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() 6

7 DECLARE terms_id_var INT; SELECT terms_id INTO terms_id_var FROM invoices WHERE invoice_id = 4; CASE terms_id_var WHEN 1 THEN SELECT 'Net due 10 days' AS Terms; WHEN 2 THEN SELECT 'Net due 20 days' AS Terms; WHEN 3 THEN SELECT 'Net due 30 days' AS Terms; ELSE SELECT 'Net due more than 30 days' AS Terms; END CASE; -- rewritten as a Searched CASE statement /* CASE WHEN terms_id_var = 1 THEN SELECT 'Net due 10 days' AS Terms; WHEN terms_id_var = 2 THEN SELECT 'Net due 20 days' AS Terms; WHEN terms_id_var = 3 THEN SELECT 'Net due 30 days' AS Terms; ELSE SELECT 'Net due more than 30 days' AS Terms; END CASE; */ CALL test(); The response 7

8 Coding Loops While Loop Syntax WHILE boolean_expression DO statement_1; [statement_2;]... END WHILE; Three types of loops: a WHILE loop, a REPEAT loop, and a simple loop. You can use LEAVE statement to go to the end of a loop. You can use the ITERATE statement to go to the beginning of a loop. See the following example: DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() DECLARE i INT DEFAULT 1; DECLARE s VARCHAR(400) DEFAULT ''; -- WHILE loop /* WHILE i < 4 DO SET s = CONCAT(s, 'i=', i, ' '); SET i = i + 1; END WHILE; */ -- REPEAT loop REPEAT SET s = CONCAT(s, 'i=', i, ' '); SET i = i + 1; UNTIL i = 4 END REPEAT; -- LOOP with LEAVE statement /* testloop : LOOP SET s = CONCAT(s, 'i=', i, ' '); SET i = i + 1; IF i = 4 THEN LEAVE testloop; 8

9 END LOOP testloop; */ SELECT s AS message; CALL test(); Using a CURSOR By default, SQL statements work with an entire result set rather than individual rows. However, sometimes, you may need to work with the data in a result set one row at a time. To do that, CURSOR is used. The syntax for using a cursor Declare a cursor DECLARE cursor_name CURSOR FOR select_statement; Declare an error handler for when no rows are found in the cursor DECLARE CONTINUE HANDLER FOR NOT FOUND handler_statement; Open the cursor OPEN cursor_name; Get column values from the row and store them in a series of variables FETCH cursor_name INTO variable1 [, variable2][, variable3]...; Close the cursor CLOSE cursor_name; Example: DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() 9

10 DECLARE invoice_id_var INT; DECLARE invoice_total_var DECIMAL(9,2); DECLARE row_not_found TINYINT DEFAULT FALSE; DECLARE update_count INT DEFAULT 0; DECLARE invoices_cursor CURSOR FOR SELECT invoice_id, invoice_total FROM invoices WHERE invoice_total - payment_total - credit_total > 0; DECLARE CONTINUE HANDLER FOR NOT FOUND SET row_not_found = TRUE; OPEN invoices_cursor; WHILE row_not_found = FALSE DO FETCH invoices_cursor INTO invoice_id_var, invoice_total_var; IF invoice_total_var > 1000 THEN UPDATE invoices SET credit_total = credit_total + (invoice_total *.1) WHERE invoice_id = invoice_id_var; SET update_count = update_count + 1; END WHILE; CLOSE invoices_cursor; SELECT CONCAT(update_count, ' row(s) updated.'); CALL test(); Declaring a condition handler Commonly used MySQL error codes 10

11 Built-in named conditions NOT FOUND occurs when a program attempts to use a FETCH statement or a SELECT statement to retrieve data and no data is found SQLEXCEPTION Occurs when any error condition other than the NOT FOUND condition occurs SQLWARNING Occurs when any error condition other than the NOT FOUND condition occurs or when any warning messages occur The syntax for declaring a condition handler DECLARE {CONTINUE EXIT} HANDLER FOR { mysql_error_code SQLSTATE sqlstate_code named_condition } handler_actions; How to declare a condition handler for a MySQL error code DECLARE CONTINUE HANDLER FOR 1329 SET row_not_found = TRUE How to declare a condition handler for a SQLSTATE code DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET row_not_found = TRUE How to declare a condition handler for a named condition DECLARE CONTINUE HANDLER FOR NOT FOUND SET row_not_found = TRUE To continue execution when an error occurs, use the CONTINUE keyword. To exit the current block of code when an error occurs, use the EXIT keyword. For a complete list of the MySQL error codes and their corresponding SQLSTATE codes, you can search the MySQL reference manual for Server Error Codes. 11

12 Example: a stored procedure that does not handle errors DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() INSERT INTO general_ledger_accounts VALUES (130, 'Cash'); SELECT '1 row was inserted.'; CALL test(); The response A stored procedure that uses a CONTINUE handler DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() DECLARE duplicate_entry_for_key INT DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR 1062 SET duplicate_entry_for_key = TRUE; INSERT INTO general_ledger_accounts VALUES (130, 'Cash'); IF duplicate_entry_for_key = TRUE THEN SELECT 'Row was not inserted - duplicate key encountered.' AS message; ELSE SELECT '1 row was inserted.' AS message; 12

13 CALL test(); Response from the system Example: a stored procedure that uses an EXIT handler to handle an error DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() DECLARE duplicate_entry_for_key INT DEFAULT FALSE; DECLARE EXIT HANDLER FOR 1062 SET duplicate_entry_for_key = TRUE; INSERT INTO general_ledger_accounts VALUES (130, 'Cash'); SELECT '1 row was inserted.' AS message; END; IF duplicate_entry_for_key = TRUE THEN SELECT 'Row was not inserted - duplicate key encountered.' AS message; CALL test(); The response from the system 13

14 Example: a stored procedure that uses a named condition to handle all errors DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() DECLARE sql_error TINYINT DEFAULT FALSE; DECLARE EXIT HANDLER FOR SQLEXCEPTION SET sql_error = TRUE; INSERT INTO general_ledger_accounts VALUES (130, 'Cash'); SELECT '1 row was inserted.' AS message; END; IF sql_error = TRUE THEN SHOW ERRORS; CALL test(); The response SHOW ERRORS statement returns a result set that contains information about the errors that resulted from the last statement in the current session. Multiple condition handlers can be declared for a single stored program. If you do that, the most specific error handlers are executed first and the least specific error handlers are executed last. The MySQL error codes and the NOT FOUND condition identify specific errors. The SQLSTATE codes identify less specific ANSI-standard errors. And the SQLEXCEPTION and SQLWARNING conditions identify general errors. Example: a stored procedure that uses multiple condition handlers 14

15 DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() DECLARE duplicate_entry_for_key INT DEFAULT FALSE; DECLARE column_cannot_be_null INT DEFAULT FALSE; DECLARE sql_exception INT DEFAULT FALSE; DECLARE EXIT HANDLER FOR 1062 SET duplicate_entry_for_key = TRUE; DECLARE EXIT HANDLER FOR 1048 SET column_cannot_be_null = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION SET sql_exception = TRUE; INSERT INTO general_ledger_accounts VALUES (NULL, 'Test'); SELECT '1 row was inserted.' AS message; END; IF duplicate_entry_for_key = TRUE THEN SELECT 'Row was not inserted - duplicate key encountered.' AS message; ELSEIF column_cannot_be_null = TRUE THEN SELECT 'Row was not inserted - column cannot be null.' AS message; ELSEIF sql_exception = TRUE THEN SHOW ERRORS; CALL test(); Transactions A transaction is a group of SQL statements that are combined in a single logical unit of task. By default, a MySQL session uses autocommit mode, which automatically automatically commits INSERT, UPDATE, and DELETE statements. 15

16 When to use transactions When you code two or more INSERT, UPDATE, or DELETE statements that affect related data. When you move rows from one table to another table by using INSERT and DELETE statements When data integrity is violated by INSERT, UPDATE, or DELETE statement. To start a transaction, use the START TRANSACTION statement. This turns off autocommit mode until the statements in the transaction are committed or rolled back. To commit the changes, code a COMMIT statement. To roll back the change, use a ROLLBACK statement. MySQL automatically commits changes after a DDL statement such as a CREATE TABLE statement. You should not code DDL statement within a transaction. Transactions are often coded within stored procedures. The following example shows a stored procedure that runs three INSERT statements as a transaction. How to create stored procedures that accept parameters Syntax of Stored Procedure (SP) CREATE PROCEDURE procedure_name ( [parameter_name_1 data_type] [, parameter_name_2 data_type]... ) sql_block Example: A SP that updates a table DROP PROCEDURE IF EXISTS update_invoices_credit_total; CREATE PROCEDURE update_invoices_credit_total ( invoice_id_param INT, credit_total_param DECIMAL(9,2) ) DECLARE sql_error INT DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET sql_error = TRUE; START TRANSACTION; UPDATE invoices 16

17 SET credit_total = credit_total_param WHERE invoice_id = invoice_id_param; IF sql_error = FALSE THEN COMMIT; ELSE ROLLBACK; -- Use the CALL statement CALL update_invoices_credit_total(56, 200); SELECT invoice_id, credit_total FROM invoices WHERE invoice_id = 56; The system responses credit_total was updated from 0.00 to Use the CALL statement within a stored procedure DROP PROCEDURE IF EXISTS test; CREATE PROCEDURE test() CALL update_invoices_credit_total(56, 300); CALL test(); SELECT invoice_id, credit_total FROM invoices WHERE invoice_id = 56; -- Reset data to original value CALL update_invoices_credit_total(56, 0); 17

18 SELECT invoice_id, credit_total FROM invoices WHERE invoice_id = 56; The syntax for declaring input and output parameters Input parameters accept values that are passed from the calling program. These values cannot be changed by the body of the stored procedure. By default, parameters are defined as input parameters. As a result, the IN keyword is optional for identifying input parameters. Output parameters store values that are passed back to the calling program. These values must be set by the body of the stored procedure. To identify an output parameter, you must use the OUT keyword. INOUT parameters can store an initial value that is passed from the calling program. The body of the SP can change this parameter. When you work with OUT parameters or INOUT parameters, the calling program typically passes a user variable to the parameter list. [IN OUT INOUT] parameter_name data_type Example: DROP PROCEDURE IF EXISTS update_invoices_credit_total; CREATE PROCEDURE update_invoices_credit_total ( IN invoice_id_param INT, IN credit_total_param DECIMAL(9,2), INOUT update_count INT ) DECLARE sql_error INT DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET sql_error = TRUE; START TRANSACTION; UPDATE invoices SET credit_total = credit_total_param WHERE invoice_id = invoice_id_param; IF sql_error = FALSE THEN SET update_count = 1; COMMIT; ELSE 18

19 SET update_count = 0; ROLLBACK; = 0; CALL update_invoices_credit_total(56, CALL update_invoices_credit_total(56, SELECT CONCAT('row_count: AS update_count; The response You can provide a default value for a parameter so that if the calling program passes a null value for the parameter, the default value is used instead. To set a default value for a parameter, you can use an IF statement to check if the parameter contains a null value. If it does, you can assign a default value to the parameter. It is a good programming practice to write SP with a list of parameters that require values first followed by parameters that allow null values. Example: DROP PROCEDURE IF EXISTS update_invoices_credit_total; CREATE PROCEDURE update_invoices_credit_total ( invoice_id_param INT, credit_total_param DECIMAL(9,2) ) DECLARE sql_error INT DEFAULT FALSE; DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET sql_error = TRUE; -- Set default values for NULL values 19

20 IF credit_total_param IS NULL THEN SET credit_total_param = 100; START TRANSACTION; UPDATE invoices SET credit_total = credit_total_param WHERE invoice_id = invoice_id_param; IF sql_error = FALSE THEN COMMIT; ELSE ROLLBACK; -- call with param CALL update_invoices_credit_total(56, 200); SELECT invoice_id, credit_total FROM invoices WHERE invoice_id = 56; -- call without param CALL update_invoices_credit_total(56, NULL); SELECT invoice_id, credit_total FROM invoices WHERE invoice_id = 56; -- reset data CALL update_invoices_credit_total(56, 0); SELECT invoice_id, credit_total FROM invoices WHERE invoice_id = 56; Validate Parameters Data validation validates the parameters in a SP before using them. The SIGNAL statement raises an error. When an error occurs, SQLSTATE code must be signaled. You may optionally specify an error message or MySQL error number. When an error is raised, MySQL returns the error to the caller in the same way that it returns errors that are raised by the database engine. The calling program can handle the error. The syntax of the SIGNAL statement SIGNAL SQLSTATE [VALUE] sqlstate_value [SET MESSAGE_TEXT = message [, MYSQL_ERRNO = mysql_error_number]] 20

21 Example: DROP PROCEDURE IF EXISTS update_invoices_credit_total; CREATE PROCEDURE update_invoices_credit_total ( invoice_id_param INT, credit_total_param DECIMAL(9,2) ) -- Validate paramater values IF credit_total_param < 0 THEN UPDATE `The credit_total column must be greater than or equal to 0.` SET x = 'This UPDATE statement raises an error'; ELSEIF credit_total_param >= 1000 THEN SIGNAL SQLSTATE '22003' SET MESSAGE_TEXT = 'The credit_total column must be less than 1000.', MYSQL_ERRNO = 1264; -- Set default values for parameters IF credit_total_param IS NULL THEN SET credit_total_param = 100; UPDATE invoices SET credit_total = credit_total_param WHERE invoice_id = invoice_id_param; CALL update_invoices_credit_total(56, NULL); CALL update_invoices_credit_total(56, -100); CALL update_invoices_credit_total(56, 1000); CALL update_invoices_credit_total(56, 0); SELECT invoice_id, credit_total FROM invoices WHERE invoice_id = 56; The response 21

22 Example: a stored procedure that validates the data in a new invoice If the data for each of the columns of the row is valid, the procedure executes an INSERT statement to insert the row. Otherwise, the procedure or database engine raises an error and exits the procedure. DROP PROCEDURE IF EXISTS insert_invoice; CREATE PROCEDURE insert_invoice ( vendor_id_param INT, invoice_number_param VARCHAR(50), invoice_date_param DATE, invoice_total_param DECIMAL(9,2), terms_id_param INT, invoice_due_date_param DATE ) DECLARE terms_id_var INT; DECLARE invoice_due_date_var DATE; DECLARE terms_due_days_var INT; -- Validate paramater values IF invoice_total_param < 0 THEN SIGNAL SQLSTATE '22003' SET MESSAGE_TEXT = 'The invoice_total column must be a positive number.', MYSQL_ERRNO = 1264; ELSEIF invoice_total_param >= THEN SIGNAL SQLSTATE '22003' SET MESSAGE_TEXT = 'The invoice_total column must be less than 1,000,000.', MYSQL_ERRNO = 1264; -- Set default values for parameters IF terms_id_param IS NULL THEN SELECT default_terms_id INTO terms_id_var FROM vendors WHERE vendor_id = vendor_id_param; ELSE SET terms_id_var = terms_id_param; 22

23 IF invoice_due_date_param IS NULL THEN SELECT terms_due_days INTO terms_due_days_var FROM terms WHERE terms_id = terms_id_var; SELECT DATE_ADD(invoice_date_param, INTERVAL terms_due_days_var DAY) INTO invoice_due_date_var; ELSE SET invoice_due_date_var = invoice_due_date_param; INSERT INTO invoices (vendor_id, invoice_number, invoice_date, invoice_total, terms_id, invoice_due_date) VALUES (vendor_id_param, invoice_number_param, invoice_date_param, invoice_total_param, terms_id_var, invoice_due_date_var); -- test CALL insert_invoice(34, 'ZXA-080', ' ', , 3, ' '); CALL insert_invoice(34, 'ZXA-082', ' ', , NULL, NULL); -- this statement raises an error CALL insert_invoice(34, 'ZXA-083', ' ', , NULL, NULL); -- clean up SELECT * FROM invoices WHERE invoice_id >= 115; DELETE FROM invoices WHERE invoice_id >= 115; The response User variable is a special type of MySQL variable that s globally available to the current user. A user variable is only available to the current user and cannot be seen or accessed by other users. A user variable is available as long as the user remains connected to the server, but it is reset when the user disconnects. A user variable can store various types including string, numeric, and date/time types. However, you do not need to declare a data type for a user variable. A user variable is available from statements coded both inside and outside of stored programs. The syntax for setting a user variable 23

24 = expression Example: Two SPs that work with the same user variable DROP PROCEDURE IF EXISTS set_global_count; DROP PROCEDURE IF EXISTS increment_global_count; CREATE PROCEDURE set_global_count ( count_var INT ) = count_var; CREATE PROCEDURE increment_global_count() + 1; CALL set_global_count(100); CALL increment_global_count(); AS count_var; The response Work with dynamic SQL Dynamic SQL is often used to build complex WHERE clauses that depende on multiple search conditions that may or may not be specified by the user. You can use a SP to build a string variable that contains a SQL statement. Then, you can use the PREPARE, EXECUTE, and DEALLOCATE statements to execute the statement contained in the string. Example: a SP that uses dynamic SQL 24

25 DROP PROCEDURE IF EXISTS select_invoices; CREATE PROCEDURE select_invoices ( min_invoice_date_param DATE, min_invoice_total_param DECIMAL(9,2) ) DECLARE select_clause VARCHAR(200); DECLARE where_clause VARCHAR(200); SET select_clause = "SELECT invoice_id, invoice_number, invoice_date, invoice_total FROM invoices "; SET where_clause = "WHERE "; IF min_invoice_date_param IS NOT NULL THEN SET where_clause = CONCAT(where_clause, " invoice_date > '", min_invoice_date_param, "'"); IF min_invoice_total_param IS NOT NULL THEN IF where_clause!= "WHERE " THEN SET where_clause = CONCAT(where_clause, "AND "); SET where_clause = CONCAT(where_clause, "invoice_total > ", min_invoice_total_param); IF where_clause = "WHERE " THEN = select_clause; ELSE = CONCAT(select_clause, where_clause); PREPARE select_invoices_statement EXECUTE select_invoices_statement; DEALLOCATE PREPARE select_invoices_statement; 25

26 CALL select_invoices(' ', 100); CALL select_invoices(' ', NULL); CALL select_invoices(null, 1000); CALL select_invoices(null, NULL); variable at runtime with parameters inserted Drop a SP SELECT invoice_id, invoice_number, invoice_date, invoice_total FROM invoices WHERE invoice_date > ' ' AND invoice_total > 100 The syntax of the DROP PROCEDURE statement DROP PROCEDURE [IF EXISTS] procedure_name 2. Stored Functions (SFs) A stored function (SF), which is also called a user defined function (UDF) or just a function, is an executable database object that contains a block of procedural SQL code. With MySQL, you can only create scalar functions which return a single value. Other DBMS SF may return a result set. To identify the data type that is returned by a function, you use RETURNS keyword in the declaration for the function. Then, in the body of the SF, RETURN keyword is used to specify the value that is returned. RETURN keyword is not allowed in a SP. A function can accept input parameters that work like the input parameters for a stored procedure. A function cannot make changes to the database such as executing an INSERT, UPDATE, or DELETE statement. To call a stored function, you can use it in any expression. Example: DROP FUNCTION IF EXISTS get_vendor_id; CREATE FUNCTION get_vendor_id ( vendor_name_param VARCHAR(50) ) RETURNS INT DECLARE vendor_id_var INT; SELECT vendor_id INTO vendor_id_var 26

27 FROM vendors WHERE vendor_name = vendor_name_param; RETURN(vendor_id_var); SELECT invoice_number, invoice_total FROM invoices WHERE vendor_id = get_vendor_id('ibm'); The response Example: a function that calculates balance due DROP FUNCTION IF EXISTS get_balance_due; CREATE FUNCTION get_balance_due ( invoice_id_param INT ) RETURNS DECIMAL(9,2) DECLARE balance_due_var DECIMAL(9,2); SELECT invoice_total - payment_total - credit_total INTO balance_due_var FROM invoices WHERE invoice_id = invoice_id_param; RETURN balance_due_var; SELECT vendor_id, invoice_number, get_balance_due(invoice_id) AS balance_due FROM invoices WHERE vendor_id = 37; 27

28 To display SPs and SFs in MySQL Workbench 28

29 SHOW PROCEDURE STATUS; Display information about the SPs. SHOW FUNCTION STATUS; Display information about the SFs. 3. Create Triggers Triggers can be executed before or after an INSERT, UPDATE, or DELETE statement is executed on a table. As a result, they provide a powerful way to enforce data consistency. A trigger is a named block of code that executes or fires (in response to an INSERT, UPDATE, or DELETE statement). A trigger can be fired before or after INSERT, UPDATE, or DELETE statement. You must specify a FOR EACH ROW clause. This creates a row-level trigger that fires once for each row that is modified. You can use the OLD and NEW keywords to get and set the values for the columns that are stored in the old row and the new row. The syntax of the CREATE TRIGGER statement CREATE TRIGGER trigger_name {BEFORE AFTER} {INSERT UPDATE DELETE} ON table_name 29

30 FOR EACH ROW sql_block Example: a trigger that corrects mixed-case state names DROP TRIGGER IF EXISTS vendors_before_update; CREATE TRIGGER vendors_before_update BEFORE UPDATE ON vendors FOR EACH ROW SET NEW.vendor_state = UPPER(NEW.vendor_state); #An update statement that fires the trigger UPDATE vendors SET vendor_state = 'wi' WHERE vendor_id = 1; SELECT vendor_name, vendor_state FROM vendors WHERE vendor_id = 1; Example: a trigger that validates line item amounts DROP TRIGGER IF EXISTS invoices_before_update; CREATE TRIGGER invoices_before_update BEFORE UPDATE ON invoices FOR EACH ROW DECLARE sum_line_item_amount DECIMAL(9,2); 30

31 SELECT SUM(line_item_amount) INTO sum_line_item_amount FROM invoice_line_items WHERE invoice_id = NEW.invoice_id; IF sum_line_item_amount!= NEW.invoice_total THEN SIGNAL SQLSTATE 'HY000' SET MESSAGE_TEXT = 'Line item total must match invoice total.'; #Update statement that fires the trigger UPDATE invoices SET invoice_total = 600 WHERE invoice_id = 100; SELECT invoice_id, invoice_total, credit_total, payment_total FROM invoices WHERE invoice_id = 100; The system response Triggers can be used to enforce rules for data consistency that cannot be enforced by constraints How to create an AFTER trigger Triggers are commonly used to store information about actions that occur in a database so these actions can be reviewed later. In particular, AFTER triggers are used to store information about a statement after it executes. Example: -- A statement that creates an audit table DROP TABLE if exists invoices_audit; CREATE TABLE invoices_audit ( vendor_id INT NOT NULL, invoice_number VARCHAR(50) NOT NULL, 31

32 invoice_total DECIMAL(9,2) NOT NULL, action_type VARCHAR(50) NOT NULL, action_date DATETIME NOT NULL ); DROP TRIGGER IF EXISTS invoices_after_insert; DROP TRIGGER IF EXISTS invoices_after_delete; -- two AFTER triggers that insert rows into the audit table CREATE TRIGGER invoices_after_insert AFTER INSERT ON invoices FOR EACH ROW INSERT INTO invoices_audit VALUES (NEW.vendor_id, NEW.invoice_number, NEW.invoice_total, 'INSERTED', NOW()); CREATE TRIGGER invoices_after_delete AFTER DELETE ON invoices FOR EACH ROW INSERT INTO invoices_audit VALUES (OLD.vendor_id, OLD.invoice_number, OLD.invoice_total, 'DELETED', NOW()); -- an INSERT statement that causes the first trigger to fire INSERT INTO invoices VALUES (115, 34, 'ZXA-080', ' ', , 0, 0, 3, ' ', NULL); -- a DELETE statement that causes the second trigger to fire DELETE FROM invoices WHERE invoice_id = 115; SELECT * FROM invoices_audit; The first CREATE TRIGGER statement creates a trigger that executes after an INSERT statement is executed on the Invoices table. This trigger inserts the new values for the vendor_id, invoice_number, invoice_total, string value INSERTED, current date and time. The second trigger works similarly. The response 32

33 View or drop triggers List all triggers in the current database SHOW TRIGGERS; List all triggers in the specified database SHOW TRIGGERS IN ap; List all triggers that begin with ven% SHOW TRIGGERS IN ap LIKE 'ven%'; A statement that drops a trigger only if it exists DROP TRIGGER IF EXISTS vendors_before_update; 4. Events An event, or scheduled event, is a named block of code that executes, or fires, according to the event scheduler. By default the event scheduler is off. As a result, before you begin working with events, you need to turn on the event scheduler. If you do not need to use events, you should turn the event scheduler off to save system resources. Check if the event scheduler is on SHOW VARIABLES LIKE 'event_scheduler'; 33

34 Events are procedural database objects that MySQL invokes at the scheduled time. An event can be invoked only once. An event can be started periodically (e.g., every Sunday at 4:00 AM). MySQL keeps a schedule that tells when events must be started. Events are used for the following cases: Events can close accounts: at end of each month or each year, for example, many accounting departments need to close their accounts. Events can turn database indicators on or off. For example, consider an airplane company database. When a flight has departed, no more reservations can be made for that flight. The column CLOSED in the FLIGHTS table must be set to YES. You can schedule an event to automatically start 20 minutes after the flight s planned departure time to complete the task. Backup database to files Example: -- a statement to check if the event scheduler is on SHOW VARIABLES LIKE 'event_scheduler'; DROP EVENT IF EXISTS one_time_delete_audit_rows; DROP EVENT IF EXISTS monthly_delete_audit_rows; CREATE EVENT one_time_delete_audit_rows ON SCHEDULE AT NOW() + INTERVAL 1 MONTH DO DELETE FROM invoices_audit WHERE action_date < NOW() - INTERVAL 1 MONTH LIMIT 100; CREATE EVENT monthly_delete_audit_rows ON SCHEDULE EVERY 1 MONTH STARTS ' :00:00' DO DELETE FROM invoices_audit WHERE action_date < NOW() - INTERVAL 1 MONTH LIMIT 100; SHOW EVENTS; SHOW EVENTS IN ap; SHOW EVENTS IN ap LIKE 'mon%'; 34

35 ALTER EVENT monthly_delete_audit_rows DISABLE; ALTER EVENT monthly_delete_audit_rows ENABLE; ALTER EVENT one_time_delete_audit_rows RENAME TO one_time_delete_audits; DROP EVENT monthly_delete_audit_rows; DROP EVENT IF EXISTS monthly_delete_audit_rows; 35

Lesson 05: How to Insert, Update, and Delete Data. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

Lesson 05: How to Insert, Update, and Delete Data. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL Lesson 05: How to Insert, Update, and Delete Data By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL The syntax of the INSERT statement INSERT [INTO] table_name [(column_list)] [DEFAULT] VALUES (expression_1

More information

Triggers and Events. Kathleen Durant PhD CS 3200

Triggers and Events. Kathleen Durant PhD CS 3200 Triggers and Events Kathleen Durant PhD CS 3200 1 Triggers Trigger: procedure that starts automatically if specified change occurs to the DBMS A trigger has three parts: Event Change to the database that

More information

Multicolumn index, stored procedure, stored function, trigger, event, and transaction examples

Multicolumn index, stored procedure, stored function, trigger, event, and transaction examples Multicolumn index, stored procedure, stored function, trigger, event, and transaction examples Multicomumn index example use company; desc employee; select * from employee; explain extended select * from

More information

Chapter 11 How to create databases, tables, and indexes

Chapter 11 How to create databases, tables, and indexes Chapter 11 How to create databases, tables, and indexes Murach's MySQL, C11 2015, Mike Murach & Associates, Inc. Slide 1 Objectives Applied Given the design for a database, write the DDL statements to

More information

Chapter 1 An introduction to relational databases and SQL

Chapter 1 An introduction to relational databases and SQL Chapter 1 An introduction to relational databases and SQL Murach's MySQL, C1 2015, Mike Murach & Associates, Inc. Slide 1 Objectives Knowledge Identify the three main hardware components of a client/server

More information

SQL Workshop. Introduction Queries. Doug Shook

SQL Workshop. Introduction Queries. Doug Shook SQL Workshop Introduction Queries Doug Shook SQL Server As its name implies: its a data base server! Technically it is a database management system (DBMS) Competitors: Oracle, MySQL, DB2 End users (that

More information

Database Management Systems

Database Management Systems Database Management Systems Design and Creation Doug Shook Database Creation Design is very important Long lasting implications How is our data being stored again? How do we manipulate data? 2 Example

More information

Chapter 7 How to code subqueries

Chapter 7 How to code subqueries Chapter 7 How to code subqueries Murach's MySQL, C7 2015, Mike Murach & Associates, Inc. Slide 1 Objectives Applied Code SELECT statements that require subqueries. Knowledge Describe the way subqueries

More information

HNDIT 1105 Database Management Systems

HNDIT 1105 Database Management Systems HNDIT 1105 Database Management Systems How to retrieve data in a single table By S. Sabraz Nawaz M.Sc. In IS (SLIIT), PGD in IS (SLIIT), BBA (Hons.) Spl. in IS (SEUSL), MIEEE, MAIS Senior Lecturer in MIT

More information

Lecture 3: Continuing SQL. Monday, February 2, 2015

Lecture 3: Continuing SQL. Monday, February 2, 2015 Lecture 3: Continuing SQL Monday, February 2, 2015 1 Announcements Homework #1 has been posted on Canvas and is due by 4pm next Monday FoCS Career Night this Wednesday from 5:00 pm to 7:30 pm CNS Spring

More information

Stored Procedure. Stored procedures or functions. CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Create Stored Routines

Stored Procedure. Stored procedures or functions. CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Create Stored Routines Stored procedures or functions CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang Stored routines (procedures and functions) are supported in MySQL 5.0. A stored

More information

Chapter 3 How to retrieve data from a single table

Chapter 3 How to retrieve data from a single table Chapter 3 How to retrieve data from a single table Murach's MySQL, C3 2015, Mike Murach & Associates, Inc. Slide 1 Objectives Applied Code SELECT statements that require any of the language elements presented

More information

Stored Procedures and Functions

Stored Procedures and Functions Stored Procedures and Functions Dichiarazione di procedure e funzioni CREATE [DEFINER = { user CURRENT_USER }] PROCEDURE sp_name ([proc_parameter[,...]]) [characteristic...] routine_body CREATE [DEFINER

More information

SQL Workshop. Database Design. Doug Shook

SQL Workshop. Database Design. Doug Shook SQL Workshop Database Design Doug Shook Data Structure Design Real-world system Database system People Tables Documents Facilities Columns Other systems Rows 2 Data Structure Design Relational database

More information

SQL User Defined Code. Kathleen Durant CS 3200

SQL User Defined Code. Kathleen Durant CS 3200 SQL User Defined Code Kathleen Durant CS 3200 1 User Session Objects Literals Text single quoted strings Numbers Database objects: databases, tables, fields, procedures and functions Can set a default

More information

SQL Workshop. Subqueries. Doug Shook

SQL Workshop. Subqueries. Doug Shook SQL Workshop Subqueries Doug Shook Subqueries A SELECT statement within a SELECT statement Four ways to code one: WHERE (*) HAVING (*) FROM SELECT Syntax is the same Rare to see GROUP BY or HAVING 2 Subqueries

More information

SQL Workshop. Summaries. Doug Shook

SQL Workshop. Summaries. Doug Shook SQL Workshop Summaries Doug Shook Aggregates Also called column functions AVG, SUM, MIN, MAX, COUNT Will use all values can use distinct if desired All except COUNT ignore null values A summary query that

More information

Chapter 4 How to retrieve data from two tables

Chapter 4 How to retrieve data from two tables Chapter 4 How to retrieve data from two tables PL/SQL, C4 2008, Mike Murach & Associates, Inc. Slide 1 Objectives Applied Use the explicit syntax to code an inner join that returns data from a single table

More information

Lecture 9: Database Design. Wednesday, February 18, 2015

Lecture 9: Database Design. Wednesday, February 18, 2015 Lecture 9: Database Design Wednesday, February 18, 2015 Agenda Review HW #2 Discuss Normalization Theory Take Quiz #3 Normal Forms 1st Normal Form (1NF): will discuss briefly 2nd Normal Form (2NF): will

More information

ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine.

ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine. 1 PL/SQL INTRODUCTION SQL does not have procedural capabilities. SQL does not provide the programming techniques of condition checking, looping and branching that is required for data before permanent

More information

SQL STORED ROUTINES. CS121: Relational Databases Fall 2017 Lecture 9

SQL STORED ROUTINES. CS121: Relational Databases Fall 2017 Lecture 9 SQL STORED ROUTINES CS121: Relational Databases Fall 2017 Lecture 9 SQL Functions 2 SQL queries can use sophisticated math operations and functions Can compute simple functions, aggregates Can compute

More information

SQL Workshop. Joins. Doug Shook

SQL Workshop. Joins. Doug Shook SQL Workshop Joins Doug Shook Inner Joins Joins are used to combine data from multiple tables into one result Requires the name of the column from the second table, along with a condition that defines

More information

Topics Fundamentals of PL/SQL, Integration with PROIV SuperLayer and use within Glovia

Topics Fundamentals of PL/SQL, Integration with PROIV SuperLayer and use within Glovia Topics Fundamentals of PL/SQL, Integration with PROIV SuperLayer and use within Glovia 1. Creating a Database Alias 2. Introduction to SQL Relational Database Concept Definition of Relational Database

More information

The SQL Procedure Language (SQL PL)

The SQL Procedure Language (SQL PL) The SQL Procedure Language (SQL PL) Tony Andrews Themis Education tandrews@themisinc.com www.themisinc.com Coding a SQL PL Procedure An SQL procedure consists of: CREATE PROCEDURE header BEGIN statement

More information

STORED PROCEDURE AND TRIGGERS

STORED PROCEDURE AND TRIGGERS STORED PROCEDURE AND TRIGGERS EGCO321 DATABASE SYSTEMS KANAT POOLSAWASD DEPARTMENT OF COMPUTER ENGINEERING MAHIDOL UNIVERSITY STORED PROCEDURES MySQL is known as the most popular open source RDBMS which

More information

Meet MariaDB Vicențiu Ciorbaru Software MariaDB Foundation * * 2017 MariaDB Foundation

Meet MariaDB Vicențiu Ciorbaru Software MariaDB Foundation * * 2017 MariaDB Foundation Meet MariaDB 10.3 Vicențiu Ciorbaru Software Engineer @ MariaDB Foundation vicentiu@mariadb.org * * What is MariaDB? MariaDB 5.1 (Feb 2010) - Making builds free MariaDB 5.2 (Nov 2010) - Community features

More information

Introduction to Computer Science and Business

Introduction to Computer Science and Business Introduction to Computer Science and Business The Database Programming with PL/SQL course introduces students to the procedural language used to extend SQL in a programatic manner. This course outline

More information

An Introduction to Stored Procedures in MySQL 5 by Federico Leven6 Apr 2011

An Introduction to Stored Procedures in MySQL 5 by Federico Leven6 Apr 2011 An Introduction to Stored Procedures in MySQL 5 by Federico Leven6 Apr 21 MySQL 5 introduced a plethora of new features - stored procedures being one of the most significant. In this tutorial, we will

More information

Chapter 8 How to work with data types

Chapter 8 How to work with data types Chapter 8 How to work with data types Murach's MySQL, C8 2015, Mike Murach & Associates, Inc. Slide 1 Objectives Applied Code queries that convert data from one data type to another. Knowledge Describe

More information

Lesson B Objectives IF/THEN. Chapter 4B: More Advanced PL/SQL Programming

Lesson B Objectives IF/THEN. Chapter 4B: More Advanced PL/SQL Programming Chapter 4B: More Advanced PL/SQL Programming Monday 2/23/2015 Abdou Illia MIS 4200 - Spring 2015 Lesson B Objectives After completing this lesson, you should be able to: Create PL/SQL decision control

More information

Instructor: Craig Duckett. Lecture 14: Tuesday, May 15 th, 2018 Stored Procedures (SQL Server) and MySQL

Instructor: Craig Duckett. Lecture 14: Tuesday, May 15 th, 2018 Stored Procedures (SQL Server) and MySQL Instructor: Craig Duckett Lecture 14: Tuesday, May 15 th, 2018 Stored Procedures (SQL Server) and MySQL 1 Assignment 3 is due LECTURE 20, Tuesday, June 5 th Database Presentation is due LECTURE 20, Tuesday,

More information

PL/SQL is a combination of SQL along with the procedural features of programming languages.

PL/SQL is a combination of SQL along with the procedural features of programming languages. (24 Marks) 5.1 What is PLSQL? PLSQL stands for Procedural Language extension of SQL. PLSQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle

More information

Programming the Database

Programming the Database Programming the Database Today s Lecture 1. Stored Procedures 2. Functions BBM471 Database Management Systems Dr. Fuat Akal akal@hacettepe.edu.tr 3. Cursors 4. Triggers 5. Dynamic SQL 2 Stored Procedures

More information

Overview. Data Integrity. Three basic types of data integrity. Integrity implementation and enforcement. Database constraints Transaction Trigger

Overview. Data Integrity. Three basic types of data integrity. Integrity implementation and enforcement. Database constraints Transaction Trigger Data Integrity IT 4153 Advanced Database J.G. Zheng Spring 2012 Overview Three basic types of data integrity Integrity implementation and enforcement Database constraints Transaction Trigger 2 1 Data Integrity

More information

ORACLE: PL/SQL Programming

ORACLE: PL/SQL Programming %ROWTYPE Attribute... 4:23 %ROWTYPE... 2:6 %TYPE... 2:6 %TYPE Attribute... 4:22 A Actual Parameters... 9:7 Actual versus Formal Parameters... 9:7 Aliases... 8:10 Anonymous Blocks... 3:1 Assigning Collection

More information

UNIT-IV (Relational Database Language, PL/SQL)

UNIT-IV (Relational Database Language, PL/SQL) UNIT-IV (Relational Database Language, PL/SQL) Section-A (2 Marks) Important questions 1. Define (i) Primary Key (ii) Foreign Key (iii) unique key. (i)primary key:a primary key can consist of one or more

More information

Lecture 08. Spring 2018 Borough of Manhattan Community College

Lecture 08. Spring 2018 Borough of Manhattan Community College Lecture 08 Spring 2018 Borough of Manhattan Community College 1 The SQL Programming Language Recent versions of the SQL standard allow SQL to be embedded in high-level programming languages to help develop

More information

Model Question Paper. Credits: 4 Marks: 140

Model Question Paper. Credits: 4 Marks: 140 Model Question Paper Subject Code: BT0075 Subject Name: RDBMS and MySQL Credits: 4 Marks: 140 Part A (One mark questions) 1. MySQL Server works in A. client/server B. specification gap embedded systems

More information

5. Single-row function

5. Single-row function 1. 2. Introduction Oracle 11g Oracle 11g Application Server Oracle database Relational and Object Relational Database Management system Oracle internet platform System Development Life cycle 3. Writing

More information

Conceptual Design. The Entity-Relationship (ER) Model

Conceptual Design. The Entity-Relationship (ER) Model Conceptual Design. The Entity-Relationship (ER) Model CS430/630 Lecture 12 Slides based on Database Management Systems 3 rd ed, Ramakrishnan and Gehrke Relationship Set Representation ssn name lot since

More information

1Z0-144 Q&As Oracle Database 11g: Program with PL/ SQL

1Z0-144 Q&As Oracle Database 11g: Program with PL/ SQL CertBus.com 1Z0-144 Q&As Oracle Database 11g: Program with PL/ SQL Pass Oracle 1Z0-144 Exam with 100% Guarantee Free Download Real Questions & Answers PDF and VCE file from: 100% Passing Guarantee 100%

More information

Oracle SQL. murach s. and PL/SQL TRAINING & REFERENCE. (Chapter 2)

Oracle SQL. murach s. and PL/SQL TRAINING & REFERENCE. (Chapter 2) TRAINING & REFERENCE murach s Oracle SQL and PL/SQL (Chapter 2) works with all versions through 11g Thanks for reviewing this chapter from Murach s Oracle SQL and PL/SQL. To see the expanded table of contents

More information

Lab # 4. Data Definition Language (DDL)

Lab # 4. Data Definition Language (DDL) Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Lab # 4 Data Definition Language (DDL) Eng. Haneen El-Masry November, 2014 2 Objective To be familiar with

More information

Database Technology. Topic 6: Triggers and Stored Procedures

Database Technology. Topic 6: Triggers and Stored Procedures Topic 6: Triggers and Stored Procedures Olaf Hartig olaf.hartig@liu.se Triggers What are Triggers? Specify actions to be performed by the DBMS when certain events and conditions occur Used to monitor the

More information

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas

SQL Functionality SQL. Creating Relation Schemas. Creating Relation Schemas SQL SQL Functionality stands for Structured Query Language sometimes pronounced sequel a very-high-level (declarative) language user specifies what is wanted, not how to find it number of standards original

More information

Database Application Development Oracle PL/SQL, part 2. CS430/630 Lecture 18b

Database Application Development Oracle PL/SQL, part 2. CS430/630 Lecture 18b Database Application Development Oracle PL/SQL, part 2 CS430/630 Lecture 18b Murach Chapter 14 How to manage transactions and locking PL/SQL, C14 2014, Mike Murach & Associates, Inc. Slide 2 Objectives

More information

IBM DB2 9.7 SQL Procedure Developer.

IBM DB2 9.7 SQL Procedure Developer. IBM 000-545 DB2 9.7 SQL Procedure Developer http://killexams.com/exam-detail/000-545 QUESTION: 105 Click the Exhibit button. Referring to the exhibit, which two statements are correct? (Choose two.) A.

More information

Listing of SQLSTATE values

Listing of SQLSTATE values Listing of values 1 of 28 5/15/2008 11:28 AM Listing of values The tables in this topic provide descriptions of codes that can be returned to applications by DB2 UDB for iseries. The tables include values,

More information

UNIT II PL / SQL AND TRIGGERS

UNIT II PL / SQL AND TRIGGERS UNIT II PL / SQL AND 1 TRIGGERS TOPIC TO BE COVERED.. 2.1 Basics of PL / SQL 2.2 Datatypes 2.3 Advantages 2.4 Control Structures : Conditional, Iterative, Sequential 2.5 Exceptions: Predefined Exceptions,User

More information

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama The Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Database Lab Lab # 2 Data Definition Language (DDL) Eng. Alaa O Shama October, 2015 Objective To be familiar

More information

MIT Database Management Systems

MIT Database Management Systems MIT 22033 Database Management Systems Lesson 04: How to retrieve data from two or more tables By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL How to code an inner join A join is used to combine columns

More information

Question: Which statement would you use to invoke a stored procedure in isql*plus?

Question: Which statement would you use to invoke a stored procedure in isql*plus? What are the two types of subprograms? procedure and function Which statement would you use to invoke a stored procedure in isql*plus? EXECUTE Which SQL statement allows a privileged user to assign privileges

More information

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL HOW TO CREATE AND MAINTAIN DATABASES AND TABLES By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL What is SQL? SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate

More information

Introduction p. 1 The Logical and Physical View of Tables p. 1 Database Types p. 4 NULLs p. 6 DDL and DML Statements p. 7 Column and Table Constraint

Introduction p. 1 The Logical and Physical View of Tables p. 1 Database Types p. 4 NULLs p. 6 DDL and DML Statements p. 7 Column and Table Constraint Preface p. xv Introduction p. 1 The Logical and Physical View of Tables p. 1 Database Types p. 4 NULLs p. 6 DDL and DML Statements p. 7 Column and Table Constraint Clauses p. 7 Sample Database p. 9 A Quick

More information

Full file at

Full file at ch2 True/False Indicate whether the statement is true or false. 1. The SQL command to create a database table is an example of DML. 2. A user schema contains all database objects created by a user. 3.

More information

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2 CMPT 354 Constraints Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers John Edgar 2 firstname type balance city customerid lastname accnumber rate branchname phone

More information

PL/SQL Block structure

PL/SQL Block structure PL/SQL Introduction Disadvantage of SQL: 1. SQL does t have any procedural capabilities. SQL does t provide the programming technique of conditional checking, looping and branching that is vital for data

More information

Relational Database Management System 2014

Relational Database Management System 2014 Unit-1: Procedural SQL data types Fill in the blank: 1. are used to defining a fully relational database. 2. Data can be presented to the user in different logical combinations, called. 3. Changes to the

More information

Lecture 17. Monday, November 17, 2014

Lecture 17. Monday, November 17, 2014 Lecture 17 Monday, November 17, 2014 DELIMITER So far this semester, we ve used ; to send all of our SQL statements However, when we define routines that use SQL statements in them, it can make distinguishing

More information

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language Information Systems Engineering SQL Structured Query Language DDL Data Definition (sub)language 1 SQL Standard Language for the Definition, Querying and Manipulation of Relational Databases on DBMSs Its

More information

SQL Stored Programs. You Can Not Do Everything in SQL SQL/PSM Cursors Recursion Triggers. Niklas Fors Stored Programs 1 / 21

SQL Stored Programs. You Can Not Do Everything in SQL SQL/PSM Cursors Recursion Triggers. Niklas Fors Stored Programs 1 / 21 SQL Stored Programs You Can Not Do Everything in SQL SQL/PSM Cursors Recursion Triggers Niklas Fors (niklas.fors@cs.lth.se) Stored Programs 1 / 21 Stored Programs SQL is not Turing complete so there are

More information

Chapter 13 Introduction to SQL Programming Techniques

Chapter 13 Introduction to SQL Programming Techniques Chapter 13 Introduction to SQL Programming Techniques Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Outline Database Programming: Techniques and Issues Embedded

More information

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel 1 In this chapter, you will learn: The basic commands

More information

COP 3718 Intermediate Database Systems. Chapter 13 Stored Procedures

COP 3718 Intermediate Database Systems. Chapter 13 Stored Procedures COP 3718 Intermediate Database Systems Chapter 13 Stored Procedures 1 Stored Routines A stored procedure is a set of SQL statements stored in a database and made available in the same way we use SQL functions

More information

1. Given the name of a movie studio, find the net worth of its president.

1. Given the name of a movie studio, find the net worth of its president. 1. Given the name of a movie studio, find the net worth of its president. CREATE FUNCTION GetNetWorth( studio VARCHAR(30) ) RETURNS DECIMAL(9,3) DECLARE worth DECIMAL(9,3); SELECT networth INTO worth FROM

More information

DATABASE DESIGN - 1DL400

DATABASE DESIGN - 1DL400 DATABASE DESIGN - 1DL400 Fall 2015 A course on modern database systems http://www.it.uu.se/research/group/udbl/kurser/dbii_ht15 Kjell Orsborn Uppsala Database Laboratory Department of Information Technology,

More information

Procedural Language Structured Query Language (PL/SQL)

Procedural Language Structured Query Language (PL/SQL) The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Database Lab (ECOM 4113) Lab 7 Procedural Language Structured Query Language (PL/SQL) Eng. Ibraheem Lubbad Structured

More information

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe Chapter 10 Outline Database Programming: Techniques and Issues Embedded SQL, Dynamic SQL, and SQLJ Database Programming with Function Calls: SQL/CLI and JDBC Database Stored Procedures and SQL/PSM Comparing

More information

Symptom. Environment. Resolution What words are reserved and cannot be used in BPC? Version 3 Validity:

Symptom. Environment. Resolution What words are reserved and cannot be used in BPC? Version 3 Validity: SAP Knowledge Base Article 1632682 - What words are reserved and cannot be used in BPC? Version 3 Validity: 16.09.2011 - active Language English Symptom What words are reserved and cannot be used in Business

More information

Basic SQL. Basic SQL. Basic SQL

Basic SQL. Basic SQL. Basic SQL Basic SQL Dr Fawaz Alarfaj Al Imam Mohammed Ibn Saud Islamic University ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation Basic SQL Structured

More information

PL/SQL. Exception. When the PL/SQL engine cannot execute the PLSQL block it raise an error. Every Oracle error has an error number

PL/SQL. Exception. When the PL/SQL engine cannot execute the PLSQL block it raise an error. Every Oracle error has an error number PL/SQL Exception When the PL/SQL engine cannot execute the PLSQL block it raise an error. Every Oracle error has an error number Exceptions must be handled by name. PL/SQL predefines some common Oracle

More information

User's Guide c-treeace SQL Explorer

User's Guide c-treeace SQL Explorer User's Guide c-treeace SQL Explorer Contents 1. c-treeace SQL Explorer... 4 1.1 Database Operations... 5 Add Existing Database... 6 Change Database... 7 Create User... 7 New Database... 8 Refresh... 8

More information

数据库系统概论讲义, 第 8 章编程 SQL,2015,3

数据库系统概论讲义, 第 8 章编程 SQL,2015,3 数据库系统概论 An Introduction to Database Systems 第八章数据库编程 (ODBC, PL/SQL) 2016, 3, 29 Programmatic SQL Three types of programmatic SQL Embedded SQL statements ISO standard specifies embedded support for C, COBOL,

More information

MySQL 5.1 Past, Present and Future MySQL UC 2006 Santa Clara, CA

MySQL 5.1 Past, Present and Future MySQL UC 2006 Santa Clara, CA MySQL 5.1 Past, Present and Future jan@mysql.com MySQL UC 2006 Santa Clara, CA Abstract Last year at the same place MySQL presented the 5.0 release introducing Stored Procedures, Views and Triggers to

More information

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management Tenth Edition Chapter 7 Introduction to Structured Query Language (SQL) Objectives In this chapter, students will learn: The basic commands and

More information

COSC344 Database Theory and Applications. Lecture 11 Triggers

COSC344 Database Theory and Applications. Lecture 11 Triggers COSC344 Database Theory and Applications Lecture 11 Triggers COSC344 Lecture 11 1 Overview Last Lecture - PL/SQL This Lecture - Triggers - Source: Lecture notes, Oracle documentation Next Lecture - Java

More information

RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND ANSWERS

RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND ANSWERS RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND ANSWERS SUMMER 2017 Q. Describe Exception handling. Explain with example. 4 Marks Exception Handling: Exception is nothing but an error. Exception can be

More information

Db2 User-Defined Functions

Db2 User-Defined Functions Db2 User-Defined Functions David Simpson Themis Education dsimpson@themisinc.com www.themisinc.com @ThemisDave @ThemisTraining Themis Education Most complete DB2 Curriculum in the industry Offerings include

More information

Trigger is a stored procedure which is called implicitly by oracle engine whenever a insert, update or delete statement is fired.

Trigger is a stored procedure which is called implicitly by oracle engine whenever a insert, update or delete statement is fired. Aim:- TRIGGERS Trigger is a stored procedure which is called implicitly by oracle engine whenever a insert, update or delete statement is fired. Advantages of database triggers: ---> Data is generated

More information

Seminar 3. Stored procedures. Global variables. Dynamic Execution. The OUTPUT clause. Cursors

Seminar 3. Stored procedures. Global variables. Dynamic Execution. The OUTPUT clause. Cursors Seminar 3. Stored procedures. Global variables. Dynamic Execution. The OUTPUT clause. Cursors Transact-SQL Server Stored Procedures A stored procedure is a group of Transact-SQL statements compiled into

More information

SQL Stored Routines Draft SQL Stored Routines. Procedural Extensions of SQL and External Routines in Transactional Context

SQL Stored Routines Draft SQL Stored Routines. Procedural Extensions of SQL and External Routines in Transactional Context SQL Stored Routines Draft 2017-06-09 www.dbtechnet.org SQL Stored Routines Procedural Extensions of SQL and External Routines in Transactional Context Authors: Martti Laiho, Fritz Laux, Ilia Petrov, Dimitris

More information

PL / SQL Basics. Chapter 3

PL / SQL Basics. Chapter 3 PL / SQL Basics Chapter 3 PL / SQL Basics PL / SQL block Lexical units Variable declarations PL / SQL types Expressions and operators PL / SQL control structures PL / SQL style guide 2 PL / SQL Block Basic

More information

EVALUATION COPY. Contents. Unauthorized reproduction or distribution is prohibited. MySQL Development

EVALUATION COPY. Contents. Unauthorized reproduction or distribution is prohibited. MySQL Development Contents Chapter 1 - Course Introduction... 9 Course Objectives... 10 Course Overview... 12 Using the Workbook... 13 Suggested References... 14 Chapter 2 - Introduction to Database Concepts and MySQL...

More information

Chapter 9 How to use functions

Chapter 9 How to use functions Chapter 9 How to use functions Murach's MySQL, C9 2015, Mike Murach & Associates, Inc. Slide 1 Objectives Applied Code queries that format numeric or date/time data. Code queries that require any of the

More information

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

Chapter # 7 Introduction to Structured Query Language (SQL) Part I Chapter # 7 Introduction to Structured Query Language (SQL) Part I Introduction to SQL SQL functions fit into two broad categories: Data definition language Data manipulation language Basic command set

More information

The PL/SQL Engine: PL/SQL. A PL/SQL Block: Declaration Section. Execution Section. Declaration Section 3/24/2014

The PL/SQL Engine: PL/SQL. A PL/SQL Block: Declaration Section. Execution Section. Declaration Section 3/24/2014 PL/SQL The PL/SQL Engine: PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle

More information

Principles of Data Management

Principles of Data Management Principles of Data Management Alvin Lin August 2018 - December 2018 Structured Query Language Structured Query Language (SQL) was created at IBM in the 80s: SQL-86 (first standard) SQL-89 SQL-92 (what

More information

Index. Symbol function, 391

Index. Symbol function, 391 Index Symbol @@error function, 391 A ABP. See adjacent broker protocol (ABP) ACID (Atomicity, Consistency, Isolation, and Durability), 361 adjacent broker protocol (ABP) certificate authentication, 453

More information

Exact Numeric Data Types

Exact Numeric Data Types SQL Server Notes for FYP SQL data type is an attribute that specifies type of data of any object. Each column, variable and expression has related data type in SQL. You would use these data types while

More information

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation

Basic SQL. Dr Fawaz Alarfaj. ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation Basic SQL Dr Fawaz Alarfaj Al Imam Mohammed Ibn Saud Islamic University ACKNOWLEDGEMENT Slides are adopted from: Elmasri & Navathe, Fundamentals of Database Systems MySQL Documentation MIDTERM EXAM 2 Basic

More information

4. Inputting data or messages to a function is called passing data to the function.

4. Inputting data or messages to a function is called passing data to the function. Test Bank for A First Book of ANSI C 4th Edition by Bronson Link full download test bank: http://testbankcollection.com/download/test-bank-for-a-first-book-of-ansi-c-4th-edition -by-bronson/ Link full

More information

SQL functions fit into two broad categories: Data definition language Data manipulation language

SQL functions fit into two broad categories: Data definition language Data manipulation language Database Principles: Fundamentals of Design, Implementation, and Management Tenth Edition Chapter 7 Beginning Structured Query Language (SQL) MDM NUR RAZIA BINTI MOHD SURADI 019-3932846 razia@unisel.edu.my

More information

Creating SQL Server Stored Procedures CDS Brownbag Series CDS

Creating SQL Server Stored Procedures CDS Brownbag Series CDS Creating SQL Server Stored Procedures Paul Litwin FHCRC Collaborative Data Services CDS Brownbag Series This is the 11th in a series of seminars Materials for the series can be downloaded from www.deeptraining.com/fhcrc

More information

Chapter 14. Active Databases. Database Systems(Part 2) p. 200/286

Chapter 14. Active Databases. Database Systems(Part 2) p. 200/286 Chapter 14 Active Databases Database Systems(Part 2) p. 200/286 Active Data? With the help of constraints (primary key, foreign key, check clauses) we increased the data semantics Anything that the database

More information

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL)

PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 4 Database Programming PROCEDURAL DATABASE PROGRAMMING ( PL/SQL AND T-SQL) AGENDA 6. Stored Functions Procedural Database Programming

More information

1 Preface. 1.1 Summary of contents

1 Preface. 1.1 Summary of contents 1 Preface DRIVE/WINDOWS provides you with access to the database system SESAM/SQL-Server V2 by means of SQL statements. This manual contains a brief description of the exact syntax of the DRIVE SQL statements

More information

Contents I Introduction 1 Introduction to PL/SQL iii

Contents I Introduction 1 Introduction to PL/SQL iii Contents I Introduction Lesson Objectives I-2 Course Objectives I-3 Human Resources (HR) Schema for This Course I-4 Course Agenda I-5 Class Account Information I-6 Appendixes Used in This Course I-7 PL/SQL

More information

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: SQL and PL/SQL Fundamentals NEW Oracle Database: SQL and PL/SQL Fundamentals NEW Duration: 5 Days What you will learn This Oracle Database: SQL and PL/SQL Fundamentals training delivers the fundamentals of SQL and PL/SQL along with the

More information

ITCS Implementation. Jing Yang 2010 Fall. Class 14: Introduction to SQL Programming Techniques (Ch13) Outline

ITCS Implementation. Jing Yang 2010 Fall. Class 14: Introduction to SQL Programming Techniques (Ch13) Outline ITCS 3160 Data Base Design and Implementation Jing Yang 2010 Fall Class 14: Introduction to SQL Programming Techniques (Ch13) Outline Database Programming: Techniques and Issues Three approaches: Embedded

More information

COMP 430 Intro. to Database Systems. Encapsulating SQL code

COMP 430 Intro. to Database Systems. Encapsulating SQL code COMP 430 Intro. to Database Systems Encapsulating SQL code Want to bundle SQL into code blocks Like in every other language Encapsulation Abstraction Code reuse Maintenance DB- or application-level? DB:

More information