1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu Teach Yourself PL/SQL in 21 Days- P5 doc

50 292 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 50
Dung lượng 2,42 MB

Nội dung

Using Oracle’s Built-In Functions 177 6 T ABLE 6.9 Masks Used with the ROUND and TRUNC Functions Mask Options Description CC , SCC Rounds or truncates to the century YYYY , SYYYY , YEAR ,Truncates to the year or rounds up to the next year after July 1st SYEAR , YYY , YY , Y IYYY , IYY , IY , I ISO year Q Truncates to the quarter or rounds up to the nearest quarter on or after the 16th day of the second month of the quarter MM , MON , MONTH , RM Truncates the month or rounds up to the next month on or after the 16th day DD , DDD , J Truncates or rounds to the day WW Same day of the week as the first day of the year IW Same day of the week as the first day of the ISO year W Same day of the week as the first day of the month Day , Dy , D Truncates or rounds to the first day of the week HH24 , HH12 , HH Truncates to the hour or rounds up to the next hour on or after 30 minutes MI Truncates to the minute or rounds up on or after 30 seconds Now that you have seen all the possible masking options, try the TRUNC function by testing it with different examples. You will first truncate the time from the system date. Remember, you still see the time displayed, but if you use TRUNC on all dates, the time is always 12:00 AM. instead of the time the date was assigned; therefore, all dates can be calculated properly regardless of time. Go ahead and execute the SQL code in Listing 6.19. L ISTING 6.19 Removing the Time from SYSDATE 1: SELECT TO_CHAR(TRUNC(SYSDATE),’MM/DD/YYYY HH:MM:SS AM’) 2: “Today’s Date and Time” 3: from DUAL; Your output appears similar to Today’s Date and Time ----------------------- 06/21/1999 12:00:00 AM Notice that the time element is still displayed, but if you were to subtract two truncated dates with the same time, you get an even number of days. One more observation is that the default for TRUNC is the same as a format mask of DD , which simply eliminates the need to worry about the time in your calculations. I NPUT O UTPUT A NALYSIS 08 7982 ch06 11.8.00 11:23 AM Page 177 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. You can test the TRUNC function by truncating the SYSDATE to the nearest quarter by exe- cuting the code in Listing 6.20. L ISTING 6.20 Truncating to the Quarter 1: SELECT TO_CHAR(TRUNC(SYSDATE,’Q’),’MM/DD/YYYY HH:MM:SS AM’) 2: “Today’s Date and Time” 3: from DUAL Assuming today’s date is 06/01/99, you get the following output: Today’s Date and Time ----------------------- 04/01/1999 12:00:00 AM This result makes sense because June is in the second quarter, and the quarter ranges from 04/01/99 to 06/30/99. Truncating to the quarter gives the beginning date for the applicable quarter. You’ll get the opportunity to test this function in the exercises at the end of the lesson. The ADD_MONTHS Function The ADD_MONTHS function adds or subtracts months from a date. Because this function is overloaded, which means that you can pass different data types to the same function or change the order of the parameters, you can specify the parameters in any order. ADD_MONTHS(date_passed, months_to_add) If months_to_add is positive, it adds months into the future. If the months_to_add number is negative, it subtracts months from date_passed . You can specify months_to_add as a fraction, but Oracle completely ignores the fraction. You can indi- cate the day level by using other Oracle functions. Another caution is that Oracle returns the same day in the resulting calculation except when the last day in one month (for example, March 31st) and the resulting month does not have as many days. (For example, April 30th is the answer to adding one month.) The following three examples in Listing 6.21 provide the same result. L ISTING 6.21 Adding Two Months to SYSDATE 1: SELECT ADD_MONTHS(SYSDATE,2) from DUAL; 2: SELECT ADD_MONTHS(SYSDATE,2.654) from DUAL; 178 Day 6 I NPUT S YNTAX A NALYSIS I NPUT O UTPUT 08 7982 ch06 11.8.00 11:23 AM Page 178 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Using Oracle’s Built-In Functions 179 6 All of these (assuming the date is 06/02/99) produce the following output: ADD_MONTH --------- 02-AUG-99 You can see what happens for the last day of the month by adding one month to March 31st, as shown in Listing 6.22. L ISTING 6.22 Adding One Month SELECT ADD_MONTHS(TO_DATE(‘31-MAR-99’),1) from DUAL; This example has the output ADD_MONTH --------- 30-APR-99 Oracle could not output April 31st because no such date exists. The NEXT_DAY Function The NEXT_DAY function returns the next date in the week for the day of the week speci- fied after the input date. The time returned is the time specified by the input date when called. NEXT_DAY(input_date_passed, day_name) The NEXT_DAY function offers a lot of possibilities. You can calculate anything from the first Monday of every month to each payday in a calendar year. You’ll start by testing the NEXT_DAY function on the SYSDATE function to find the next Monday. Assume the SYSDATE is June 3, 1999. Your own results will differ when you execute the code in Listing 6.23. L ISTING 6.23 Finding the First Monday After the Current Date and Time 1: SELECT TO_CHAR(NEXT_DAY(SYSDATE,’Monday’),’MM/DD/YYYY HH:MM:SS AM’) 2: “Next_Day” 3: from DUAL; O UTPUT I NPUT O UTPUT S YNTAX A NALYSIS I NPUT 08 7982 ch06 11.8.00 11:23 AM Page 179 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. The result returned for the SYSDATE of June 3, 1999 is Next_Day ----------------------- 06/07/1999 07:06:38 AM The first Monday after the date is June 7, 1999. Because you are using the SYSDATE ,the corresponding time value is returned when the function is called. You can find the first Monday for August 1999 by executing the code in Listing 6.24. L ISTING 6.24 Finding the First Monday in the Month of August 1: SELECT TO_CHAR(NEXT_DAY(‘01-AUG-99’,’Monday’),’MM/DD/YYYY HH:MM:SS AM’) 2: “Next_Day” 3: from DUAL; Your output is Next_Day ----------------------- 08/02/1999 12:00:00 AM Although the first Monday in August is 08/02/99, is there a logic problem here? If you repeat the example but use a month in which Monday is the first day of the month, what happens? Execute the code in Listing 6.25. L ISTING 6.25 Finding the First Monday in the Month of September 1: SELECT TO_CHAR(NEXT_DAY(‘01-MAY-00’,’Monday’),’MM/DD/YYYY HH:MM:SS AM’) 2: “Next_Day” 3: from DUAL; Your output is Next_Day ----------------------- 05/08/2000 12:00:00 AM The result is definitely not what you had in mind! The NEXT_DAY function returns the next day of the day specified. If the day of the week specified matches the input date, it adds one week to the input date. If you want to calculate the first occur- rence of any day in the month, always use the end date of the previous month. Review the proper code in Listing 6.26. 180 Day 6 O UTPUT A NALYSIS I NPUT O UTPUT A NALYSIS I NPUT O UTPUT A NALYSIS 08 7982 ch06 11.8.00 11:23 AM Page 180 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Using Oracle’s Built-In Functions 181 6 L ISTING 6.26 The Proper Method to Find the First Monday in a Given Month 1: SELECT TO_CHAR(NEXT_DAY(‘30-APR-00’,’Monday’),’MM/DD/YYYY HH:MM:SS AM’) 2: “Next_Day” 3: from DUAL; Your output is Next_Day ----------------------- 05/01/2000 12:00:00 AM You finally have the proper logic for what you intended to find. The LAST_DAY Function The LAST_DAY function provides the last day of the given month. A useful purpose is to determine how many days are left in the given month. LAST_DAY(input_date_passed) You will compute the last days in the month when summer officially starts from 1999. Execute the code in Listing 6.27. L ISTING 6.27 Finding the Last Day of the Month Starting Summer 1: SELECT TO_CHAR(LAST_DAY(‘30-JUN-99’),’MM/DD/YYYY HH:MM:SS AM’) “Last_Day” 2: from DUAL; Your output is Last_Day ----------------------- 06/30/1999 12:06:00 AM I purposefully used the last day of the month to illustrate an important fact. Unlike NEXT_DAY , which adds one week if the day of the week specified is the same as the input date, the LAST_DAY function always returns the last day of the month even if the input date is the same. You can take this one step further and see how many days of summer exist in the month of June by subtracting the last day of the month by the start date of summer. Execute Listing 6.28 to see the result. I NPUT O UTPUT S YNTAX I NPUT O UTPUT A NALYSIS 08 7982 ch06 11.8.00 11:23 AM Page 181 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. L ISTING 6.28 Calculating the Number of Days of Summer in June 1: SELECT LAST_DAY(‘20-JUN-99’) “Last_Day”, 2: LAST_DAY(‘20-JUN-99’) - TO_DATE(‘20-JUN-99’) “Days_Summer” 3: from DUAL; Your output is Last_Day Days_Summer --------------------- 30-JUN-99 10 The MONTHS_BETWEEN Function The MONTHS_BETWEEN function returns the number of months between two given dates. If the day is the same in both months, you get an integer value returned. If the day is dif- ferent, you get a fractional result based upon a 31-day month. If the second date is prior to the first date, the result is negative. MONTHS_BETWEEN(input_date1,input_date2) You can see all the possible returned values by executing the code in Listing 6.29. L ISTING 6.29 Experimenting with MONTHS_BETWEEN 1: SELECT MONTHS_BETWEEN(‘25-DEC-99’,’02-JUN-99’) “Fractional”, 2: MONTHS_BETWEEN(‘02-FEB-99’,’02-JUN-99’) “Integer” 3: from DUAL; Your output is Fractional Integer ---------- --------- 6.7419355 -4 182 Day 6 I NPUT O UTPUT S YNTAX I NPUT O UTPUT Who cares about seeing the fractional part of a 31-day month? To convert the fraction to days, simply multiply the TRUNC value of the fractional part by 31. If you want to display the month, use TRUNC on this value. Tip 08 7982 ch06 11.8.00 11:23 AM Page 182 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Using Oracle’s Built-In Functions 183 6 The NEW_TIME Function Have you ever wondered what time it is in Germany? Would your phone call wake up your friend in the middle of the night? The NEW_TIME function enables you to find out the time in the time zones listed in Table 6.10 by simply passing the date and time of the first zone and specifying the second zone. NEW_TIME(input_date_and_time, time_zone1, time_zone2) See Table 6.10 for the valid time zones. T ABLE 6.10 Time Zones Time Zone Abbreviation Time Zone Description AST Atlantic Standard Time ADT Atlantic Daylight Savings Time BST Bering Standard Time BDT Bering Daylight Savings Time CST Central Standard Time CDT Central Daylight Savings Time EST Eastern Standard Time EDT Eastern Daylight Savings Time GMT Greenwich Mean Time (the date line!) HST Alaska-Hawaii Standard Time HDT Alaska-Hawaii Daylight Savings Time MST Mountain Standard Time MDT Mountain Daylight Savings Time NST Newfoundland Standard Time PST Pacific Standard Time PDT Pacific Daylight Savings Time YST Yukon Standard Time YDT Yukon Daylight Savings Time You can compute the date and time difference between Chicago and Los Angeles by specifying Central Daylight Time to Pacific Daylight Time. Enter and execute the code in Listing 6.30. S YNTAX 08 7982 ch06 11.8.00 11:23 AM Page 183 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. L ISTING 6.30 Time Change from Chicago to Los Angeles 1: SELECT TO_CHAR(NEW_TIME(TO_DATE(‘060299 01:00:00 AM’, 2: ‘MMDDYY HH:MI:SS AM’), 3: ‘CDT’,’PDT’), ‘DD-MON-YY HH:MI:SS AM’) “Central to Pacific” 4: from DUAL; 184 Day 6 I NPUT Remember, minutes are expressed as MI , not MM . This is a common mistake! Tip Your output is Central to Pacific ----------------------- 01-JUN-99 11:00:00 PM Because there is a two-hour time difference, you not only see the revised time, but also the revised date. I guess you truly can go back in time! O UTPUT In a database that traverses time zones, you might want to store the time and date for all entries in one standardized time zone, along with the time zone abbreviation from the original time zone. This arrangement saves you a lot of time and coding when designing the database. Tip A NALYSIS The ROUND Function ROUND is similar to the TRUNC function. In fact, it uses the same format mask as TRUNC in Table 6.9. This function enables you to round up or down based upon the format mask. The default mask when specifying a DATE value is DD . Some useful purposes for this are • Rounding to the nearest minute for billing cellular-based calls • Rounding to closest month to determine a pay period ROUND(input_date_and_time_or_number, rounding_specification) You can practice rounding to the nearest minute to charge people who use cellular phones by entering the code in Listing 6.31. S YNTAX 08 7982 ch06 11.8.00 11:24 AM Page 184 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Using Oracle’s Built-In Functions 185 6 L ISTING 6.31 Rounding to the Nearest Minute 1: SELECT TO_CHAR(ROUND(TO_DATE(‘060299 01:00:35 AM’, 2: ‘MMDDYY HH:MI:SS AM’), 3: ‘MI’), ‘DD-MON-YY HH:MI:SS AM’) “Rounded to nearest Minute” 4: from DUAL; Your output is Rounded to nearest Minute --------------------------- 02-JUN-99 01:01:00 AM 10 Because the seconds were 30 or greater, this example rounded to the next minute at 1:01 from 1:00. Had the number of seconds been 22, the return value would be 1:00. You should test this code on your own. The TRIM Function The TRIM function truncates leading and trailing characters from a specified string. This is equivalent to using the LTRIM and RTRIM functions simultaneously. TRIM ([LEADING/TRAILING/BOTH], trim_character FROM trim source) You can practice the TRIM function to remove leading and trailing zeroes from a specified number by entering the code in Listing 6.32. L ISTING 6.32 TRIM Leading and Trailing Zeroes SELECT TRIM (0 FROM 067270676800) “TRIM Example” FROM DUAL; Your output is TRIM Example ------------ 672706768 The TRIM function lets us remove all unwanted leading and trailing zeroes from the specified number. Summary Today, you discovered only a fraction of Oracle’s powerful built-in functions. Today’s lesson stressed the importance of converting data and working with dates. I highly rec- ommend that you refer to Appendix B to review the rest of the functions. A final tip: Punctuation is important! I NPUT O UTPUT A NALYSIS S YNTAX I NPUT O UTPUT A NALYSIS 08 7982 ch06 11.8.00 11:24 AM Page 185 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Q&A QAre all the functions available within PL/SQL? A No. Several functions can be used in SQL only. Q Must I use Oracle’s built-in functions? A No. You can always create your own similar functions, but when speed is of the essence, why reinvent the wheel? Use the built-in functions whenever possible. Q What date does the Julian system start counting from? A January 1, 4712 BC. Q When using TO_DATE , is the format mask important? A Not just a little bit important, but very important and required! Without the proper format mask, you will most certainly get an Oracle error message. QHow long should the number format mask be? A At least equal to or greater than the length of the largest value. Q What function allows you to perform mathematical computations on char- acter strings? A TO_NUMBER converts character strings to numbers so that you can perform any mathematical calculations you want. Q Where does the SYSDATE date and time originate? A If you are using Personal Oracle, the system date and time come from the PC’s internal clock. If you are in a client/server environment, the system date and time are pulled from the server. Workshop Use the following workshop to test your ability to understand and use several of Oracle’s built-in functions. The answers to the quiz and exercises appear in Appendix A, “Answers.” Quiz 1. True or False: All functions are accessible within PL/SQL. 2. What function do I use to combine two strings together? 3. What function converts ‘11/28/99’ to an Oracle DATE ? 4. In a VARCHAR2 string, each string can be a variable length. What function do you use to determine the length so that you can search through the entire string? 186 Day 6 08 7982 ch06 11.8.00 11:24 AM Page 186 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... prompt PUT_LINE The code in Listing 7.2 illustrates the PUT_LINE command line that you can include inside a procedure INPUT LISTING 7.2 The PUT_LINE Command Within a Procedure CREATE OR REPLACE PROCEDURE emp_change_s (i_emp_id IN integer) AS BEGIN UPDATE employee set pay_type = ‘S’ WHERE emp_id = i_emp_id; DBMS_OUTPUT.PUT_LINE (‘New Pay Type = ‘ || ‘S’); END emp_change_s; debug Line The following statements... program code into logical groups for easier maintenance and implementation Additionally, these groups have built -in error trapping to prevent the code from abnormally stopping during processing In today’s lesson on procedures, packages, errors, and exceptions, you will learn about • Creating procedures • Invoking stored procedures • Invoking rights for procedure • Creating packages • Trapping errors... objects belonging to the user • user_object_size—The errors on all stored objects in the database PL/SQL objects in the database text source of all stored objects in the database user’s PL/SQL objects The code in Listing 7.4 queries the user_errors view to obtain information about the current errors on a procedure owned by user_01 INPUT/ OUTPUT LISTING 7.4 Viewing Errors in a Database SELECT LINE, TYPE,... message PROCEDURE Listing 7.3 re-creates the procedure named emp_change_s INPUT LISTING 7.3 Re-creating a Procedure By Using OR REPLACE CREATE OR REPLACE PROCEDURE emp_change_s (i_emp_id IN integer) AS BEGIN UPDATE employee set pay_type = ‘S’ WHERE emp_id = i_emp_id; END emp_change_s; Invoking Stored Procedures You can invoke procedures from many different environments, including SQL*Plus and Oracle*Forms... exceptions Also, new instances of SQL statements are created at each level in the recursive procedure NEW TERM 7 198 Day 7 NEW TERM With recursive logic, the procedure must be able to terminate itself at some predefined point, or the recursion would last forever This point of termination is defined in a terminating condition The following code example uses a conditional statement to terminate the recursive... employee_maint AS Procedure emp_change_s (I_emp_id IN intger); Procedure emp_change_h (I_emp_id IN integer); Function emp_rate (rate number) RETURN number; End employee_maint; The package employee_maint is first defined in the package declaration This declaration makes the existence of the package known to the domain of the database instance Hence it can be called by any program in the instance that... overloading is with the package DBMS_OUTPUT, in which the PUT_LINE procedure is called numerous times to produce output lines of different datatypes NEW TERM The following example illustrates the definition of two overloaded local procedures: DECLARE PROCEDURE compute_sales (begin_date in date) RETURN boolean procedure is BEGIN RETURN begin_date > :start_date; END; PROCEDURE compute_sales (sales _in in date)... BEGIN RETURN sales _in > :sales_target; END; 1st example of overloaded When the PL/SQL engine encounters a call to compute_sales, the compiler executes the module in the body that has the correct and matching module header Using Recursive Procedures A recursive procedure is a procedure that calls itself Each recursive call creates a new instance of any object declared in the procedure, including... calling environment after execution pl/sql body code—The , logic of the procedure There must be at least one PL/SQL statement, or an error occurs The code shown in Listing 7.1 creates a simple stored procedure named emp_change_s This procedure accepts one argument, the emp_id parameter INPUT LISTING 7.1 Creating a Stored Procedure CREATE OR REPLACE PROCEDURE emp_change_s (i_emp_id IN integer) AS BEGIN... In this case, the stored procedure emp_change_s is called with parameter i_emp_id You can see this in the line of code immediately after the BEGIN statement When the stored procedure is invoked and successfully runs, control of the program is returned to the next line of code immediately following the procedure invocation line ANALYSIS Another example of the same procedure being executed from within . The code in Listing 7.2 illustrates the PUT_LINE command line that you can include inside a procedure. L ISTING 7.2 The PUT_LINE Command Within a Procedure. to remove leading and trailing zeroes from a specified number by entering the code in Listing 6.32. L ISTING 6.32 TRIM Leading and Trailing Zeroes SELECT

Ngày đăng: 15/12/2013, 05:15

TỪ KHÓA LIÊN QUAN