
- •4.1 Цель работы
- •4.2 Методические указания к выполнению работы
- •4.3 Теоретические сведения
- •Общие сведения об управляющих конструкциях
- •4.4 Примеры создания и использования функций
- •Создание и работа с пользовательскими функциями
- •4.5 Порядок выполнения лабораторной работы ( 3 задания)
- •4.6 Контрольные вопросы
- •4.7 Указания к оформлению отчета
- •Заполнение таблиц
4.5Порядок выполнения лабораторной работы ( 3 задания)
1.Задание общее (на 6 баллов). Проверить работоспособность примеров, приведенных в описании лабораторной работы (п. 4.4). В случае обнаружения ошибок – исправить их. В отчете привести результат выполнения. Ответить на вопросы.
2.Задание общее (на 9 баллов ). Написать функцию, которая получает на вход тип склада (поле
Storage_have), а возвращает суммарный объем складов такого типа. Написать скрипт, запустив который, можно проверить работоспособность функции. Скрипт и функция должны содержать комментарии. Объяснить суть выполненной работы.
3. Задание по вариантам (на 12 баллов). В предложенных заданиях (по варианту) необходимо выполнить следующее:
•Сделать анализ предложенной программы и выявить возможные ошибки.
•Определить отсутствующие объекты и создать их ( см. прил. Б.).
•Дать комментарий на украинском (русском) языках вместо английского. Внести дополнительные комментарии.
•Создать, отладить и выполнить предложенный скрипт.
По результатам работы оформить отчет (п. 4.7).
Вариант №1
SET serveroutput on DECLARE
/* Declare variables to be used in this block. */
v_Num1 |
NUMBER := 1; |
v_Num2 |
NUMBER := 2; |
v_String1 |
VARCHAR2(50) := 'Hello World!'; |
v_String2 |
VARCHAR2(50) := ' -- This message brought to you by PL/SQL!'; |
v_OutputStr VARCHAR2(50); BEGIN
/* First, insert two rows into temp_table, using the values of the variables. */
INSERT INTO temp_table (num_col, char_col) VALUES (v_Num1, v_String1);
INSERT INTO temp_table (num_col, char_col) VALUES (v_Num2, v_String2);
/* Now query temp_table for the two rows we just inserted, and output them to the screen using the DBMS_OUTPUT package. */
SELECT char_col INTO v_OutputStr
FROM temp_table
WHERE num_col = v_Num1; DBMS_OUTPUT.PUT_LINE(v_OutputStr);
SELECT char_col INTO v_OutputStr
FROM temp_table
WHERE num_col = v_Num2; DBMS_OUTPUT.PUT_LINE(v_OutputStr);
END;
/
Вариант №2
DECLARE
v_Department CHAR(3); /* Variable to hold the 3 character department name */
v_Course NUMBER; /* Variable to hold the course number */ BEGIN
/* Insert the course identified by v_Department and v_Course into the classes table in the database. */
INSERT INTO classes (department, course) VALUES (v_Department, v_Course);
END;
/
BEGIN
/* We are now inside a comment. If we were to begin another comment such as /* this */ it would be illegal. */
NULL;
END;
/
Вариант №3
SET serveroutput on <<l_InsertIntoTemp>> DECLARE
/* Declare variables to be used in this block. */
v_Num1 |
NUMBER := 3; |
v_Num2 |
NUMBER := 4; |
v_String1 |
VARCHAR2(50) := 'Hello World!'; |
v_String2 |
VARCHAR2(50) := ' -- This message brought to you by PL/SQL!'; |
v_OutputStr VARCHAR2(50); BEGIN
/* First, insert two rows into temp_table, using the values of the variables. */
INSERT INTO temp_table (num_col, char_col) VALUES (v_Num1, v_String1);
INSERT INTO temp_table (num_col, char_col) VALUES (v_Num2, v_String2);
/* Now query temp_table for the two rows we just inserted, and output them to the screen using the DBMS_OUTPUT package. */
SELECT char_col INTO v_OutputStr
FROM temp_table
WHERE num_col = v_Num1; DBMS_OUTPUT.PUT_LINE(v_OutputStr);
SELECT char_col
INTO v_OutputStr
FROM temp_table
WHERE num_col = v_Num2; DBMS_OUTPUT.PUT_LINE(v_OutputStr);
END l_InsertIntoTemp;
/
Вариант №4
DECLARE
v_NumberSeats rooms.number_seats%TYPE; v_Comment VARCHAR2(35);
BEGIN
/* Retrieve the number of seats in the room identified by ID 99999. Store the result in v_NumberSeats. */
SELECT number_seats INTO v_NumberSeats FROM rooms
WHERE room_id = 99999; IF v_NumberSeats < 50 THEN v_Comment := 'Fairly small';
ELSIF v_NumberSeats < 100 THEN v_Comment := 'A little bigger'; ELSE
v_Comment := 'Lots of room'; END IF;
END;
/
Вариант №5
BEGIN
FOR v_Counter IN 1..50 LOOP INSERT INTO temp_table
VALUES (v_Counter, 'Loop Index'); END LOOP;
END;
/
DECLARE
v_Counter BINARY_INTEGER := 1; BEGIN
--Test the loop counter before each loop iteration to
--insure that it is still less than 50.
WHILE v_Counter <= 50 LOOP INSERT INTO temp_table
VALUES (v_Counter, 'Loop index'); v_Counter := v_Counter + 1;
END LOOP; END;
/
Вариант №6
DECLARE
v_Major students.major%TYPE;
v_CreditIncrease NUMBER := 3;
BEGIN
--This UPDATE statement will add 3 to the current_credits
--field of all students who are majoring in History.
v_Major := 'History'; UPDATE students
SET current_credits = current_credits + v_CreditIncrease WHERE major = V_Major;
END;
/
Вариант №7
DECLARE
v_Counter BINARY_INTEGER := 1; BEGIN
LOOP
--Insert a row into temp_table with the current value of the
--loop counter.
INSERT INTO temp_table
VALUES (v_Counter, 'Loop index'); v_Counter := v_Counter + 1;
--Exit condition - when the loop counter > 50 we will
--break out of the loop.
EXIT WHEN v_Counter > 50; END LOOP;
END;
/
Вариант №8
DECLARE
TYPE t_Rec1Type IS RECORD ( Field1 NUMBER,
Field2 VARCHAR2(5));
TYPE t_Rec2Type IS RECORD ( Field1 NUMBER,
Field2 VARCHAR2(5)); v_Rec1 t_Rec1Type; v_Rec2 t_Rec2Type; BEGIN
/* Even though v_Rec1 and v_Rec2 have the same field names and field types, the record types themselves are different. This is an illegal assignment which raises PLS-382. */
v_Rec1 := v_Rec2;
/* However, the fields are the same type, so the following are legal assignments. */
v_Rec1.Field1 := v_Rec2.Field1; v_Rec2.Field2 := v_Rec2.Field2;
END;
/
Вариант №9
DECLARE
TYPE t_NumberTable IS TABLE OF NUMBER INDEX BY BINARY_INTEGER;
v_Numbers t_NumberTable; v_Total NUMBER;
BEGIN
-- Insert 50 rows into the table. FOR v_Counter IN 1..50 LOOP
v_Numbers(v_Counter) := v_Counter; END LOOP;
v_Total := v_Numbers.COUNT; END;
/
Вариант №10
SET serveroutput on DECLARE
TYPE t_ValueTable IS TABLE OF VARCHAR2(10) INDEX BY BINARY_INTEGER;
v_Values t_ValueTable; BEGIN
-- Insert rows into the table. v_Values(1) := 'One'; v_Values(3) := 'Three'; v_Values(-2) := 'Minus Two'; v_Values(0) := 'Zero'; v_Values(100) := 'Hundred';
DBMS_OUTPUT.PUT_LINE('Before DELETE, COUNT=' || v_Values.COUNT); v_Values.DELETE(100); -- Removes 'Hundred' DBMS_OUTPUT.PUT_LINE('After first DELETE, COUNT=' || v_Values.COUNT); v_Values.DELETE(1,3); -- Removes 'One' and 'Three'
DBMS_OUTPUT.PUT_LINE('After second DELETE, COUNT=' || v_Values.COUNT); v_Values.DELETE; -- Removes all remaining values DBMS_OUTPUT.PUT_LINE('After last DELETE, COUNT=' || v_Values.COUNT); END;
/
Вариант №11
DECLARE
TYPE t_FirstNameTable IS TABLE OF students.first_name%TYPE INDEX BY BINARY_INTEGER;
FirstNames t_FirstNameTable; BEGIN
-- Insert rows into the table. FirstNames(1) := 'Scott';
FirstNames(3) := 'Joanne';
-- Check to see if rows exist.
IF FirstNames.EXISTS(1) THEN
INSERT INTO temp_table (char_col) VALUES ('Row 1 exists!');
ELSE
INSERT INTO temp_table (char_col) VALUES ('Row 1 doesn''t exist!');
END IF;
IF FirstNames.EXISTS(2) THEN
INSERT INTO temp_table (char_col) VALUES ('Row 2 exists!');
ELSE
INSERT INTO temp_table (char_col) VALUES ('Row 2 doesn''t exist!');
END IF; END;
/
Вариант №12
DECLARE
TYPE t_NameTable IS TABLE OF students.first_name%TYPE INDEX BY BINARY_INTEGER;
v_Names t_NameTable; v_EmptyTable t_NameTable;
BEGIN
/* Assign some rows to v_Names. */ v_Names(1) := 'Scott';
v_Names(2) := 'Lefty'; v_Names(3) := 'Susan';
/* Delete everything in v_Names */ v_Names := v_EmptyTable;
END;
/
Вариант №13
DECLARE
--Define a record to match some fields in the students table.
--Note the use of %TYPE for the fields.
TYPE t_StudentRecord IS RECORD (
FirstName students.first_name%TYPE,
LastName students.last_name%TYPE,
Major students.major%TYPE);
-- Declare a variable to receive the data. v_Student t_StudentRecord;
BEGIN
--Retrieve information about student with ID 10,000.
--Note how the query is returning columns which match the
-- fields in v_Student.
SELECT first_name, last_name, major INTO v_Student
FROM students WHERE ID = 10000;
END;
/
Вариант №14
SET serveroutput on DECLARE
TYPE t_StudentTable IS TABLE OF students%ROWTYPE INDEX BY BINARY_INTEGER;
/* Each element of v_Students is a record */ v_Students t_StudentTable;
BEGIN
/* Retrieve the record with id = 10,001 and store it into v_Students(10001) */
SELECT *
INTO v_Students(10001) FROM students WHERE id = 10001;
v_Students(10001).first_name := 'Larry'; DBMS_OUTPUT.PUT_LINE(v_Students(10001).first_name);
END;
/
Вариант №15
DECLARE
v_NumIterations NUMBER; BEGIN
--Loop from 1 to 500, inserting these values into temp_table.
--Commit every 50 rows.
FOR v_LoopCounter IN 1..500 LOOP
INSERT INTO temp_table (num_col) VALUES (v_LoopCounter); v_NumIterations := v_NumIterations + 1;
IF v_NumIterations = 50 THEN COMMIT;
v_NumIterations := 0; END IF;
END LOOP; END;
/
Вариант №16
INSERT INTO classes
(department, course, description, max_students, current_students, num_credits, room_id)
VALUES ('CS', 101, 'Computer Science 101', 50, 10, 4, 99998); BEGIN
UPDATE rooms
SET room_id = room_id - 1000; ROLLBACK WORK;
END;
/
Вариант №17
DECLARE
v_NumCredits classes.num_credits%TYPE; BEGIN
/* Assign to v_NumCredits */ v_NumCredits := 3; UPDATE CLASSES
SET num_credits = v_NumCredits WHERE department = 'HIS'
AND course = 101; END;
/
Вариант №18
DECLARE
v_StudentCutoff NUMBER; BEGIN
v_StudentCutoff := 10;
--Delete any classes which don't have enough students registered. DELETE FROM classes
WHERE current_students < v_StudentCutoff;
--Delete any Economics students who don't have any credits yet. DELETE FROM students
WHERE current_credits = 0 AND major = 'Economics';
END;
/
Вариант №19
DECLARE
v_StudentID students.id%TYPE; BEGIN
-- Retrieve a new student ID number SELECT student_sequence.NEXTVAL INTO v_StudentID
FROM dual;
-- Add a row to the students table
INSERT INTO students (id, first_name, last_name) VALUES (v_StudentID, 'Timothy', 'Taller');
--Add a second row, but use the sequence number directly
--in the INSERT statement.
INSERT INTO students (id, first_name, last_name) VALUES (student_sequence.NEXTVAL, 'Patrick', 'Poll');
END;
/
Вариант №20
DECLARE
v_StudentRecord students%ROWTYPE; v_Department classes.department%TYPE; v_Course classes.course%TYPE;
BEGIN
--Retrieve one record from the students table, and store it
--in v_StudentRecord. Note that the WHERE clause will only
--match one row in the table.
--Note also that the query is returning all of the fields in
--the students table (since we are selecting *). Thus the
--record into which we fetch is defined as students%ROWTYPE. SELECT *
INTO v_StudentRecord FROM students WHERE id = 10000;
--Retrieve two fields from the classes table, and store them
--in v_Department and v_Course. Again, the WHERE clause will
--only match one row in the table.
SELECT department, course INTO v_Department, v_Course FROM classes
WHERE room_id = 99997; END;
/