Вы находитесь на странице: 1из 2

DECLARE

v_addr_id NUMBER;
v_joey_id NUMBER;
v_friend_count NUMBER;
BEGIN
-- Find out Joey’s address id and put it in our variable.
SELECT fa.address_id, fn.friend_id
INTO v_addr_id, v_joey_id
FROM friend_name fn, friend_address fa
WHERE fn.friend_id = fa.friend_id
AND UPPER(fn.LAST_name) = 'TRIBIANI';

/*
Now we have the address_id, find out how many other friends
live there.
We need to exclude Joey himself from our count, obviously.
*/

SELECT COUNT(*)
INTO v_friend_count
FROM friend_address
WHERE address_id = v_addr_id
AND friend_id <> v_joey_id;

-- The number of friends is in our variable. Print it out to


the screen.
DBMS_OUTPUT.PUT_LINE('The number of friends that live with
Joey is '||v_friend_count);

END;
Value Assignment

But first I must introduce you to value assignment.

You’ll remember that I said that variables are like Tupperware containers that we store
values in. And I showed you how, using SELECT … INTO, we can put values into our
variables. However, this is not the only – or even the most popular – way of assigning
values in PL/SQL. That honour goes to the following symbol:

:=

Here are some examples of it in use (assume that we have already declared our
variables v_number, v_varchar2, v_date and v_boolean):

v_number := 12;
v_number := 2 * 2;
v_number := v_number + 21;
v_varchar2 := 'Mike Tyson is a snotty little girl';
v_varchar2 := 'I am going to concatenate this string'||' with
this one';
v_date := SYSDATE;
v_date := SYSDATE + 365;
v_boolean := TRUE; -- TRUE is a Boolean value; 'TRUE' is a
varchar2 string.
v_boolean := FALSE;

It is important to point out that the assignment symbol (:=) is completely different from
the equals to sign in PL/SQL. In PL/SQL we use the equals to sign to create Boolean
expressions (2+2=4 is TRUE); to assign values to variables we always use :=.

Loops cont’d

Let’s write an anonymous block in which we loop through all the addresses in our
ADDRESS table and print out the names of the people who have ever lived there.

DECLARE
v_string VARCHAR2(500); -- when declaring a varchar2
variable you must specify its size. This one can take 500
characters.

BEGIN
-- Loop round all our addresses.
FOR i IN (SELECT *
FROM address) LOOP
v_string := 'Apartment '||i.apartment||',
'||i.house_no||' '||i.street||', '||i.city||' '||i.zipcode;
dbms_output.put_line(v_string);
-- Now let's find everyone who has lived at this
address.
FOR j IN (SELECT fn.first_name, fn.last_name
FROM friend_name fn,
friend_address fa
WHERE fa.address_id =
i.address_id
AND fn.friend_id = fa.friend_id)
LOOP

v_string := j.first_name||'
'||j.last_name;
dbms_output.put_line(v_string);
END LOOP;
END LOOP;
END;

Вам также может понравиться