Oracle For Absolute Beginners: Part 5 - PL/SQL
Oracle For Absolute Beginners: Part 5 - PL/SQL
PL/SQL
A wise man* once said, all software programming is about hoops and loops. You take some
variables, give them hoops to jump through and, depending on their success or failure, you give
them some actions to loop through a number of times. Might sound basic, but that’s what all
/*
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;
v_date := SYSDATE;
v_date := SYSDATE + 365;
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);
BEGIN
-- Loop round all our addresses.
FOR i IN (SELECT *
FROM address) LOOP
v_address := 'Apartment '||i.apartment||', '||
i.house_no||' '||i.street||', '||i.city||' '||i.zipcode;
dbms_output.put_line(v_address);
v_curr_resident := NULL;
v_past_resident := NULL;
-- Now let's find everyone who has lived at this
address.
FOR j IN (SELECT fn.first_name, fn.last_name,
fa.moved_in, fa.moved_out
FROM friend_name fn,
friend_address fa
WHERE fa.address_id =
i.address_id
AND fn.friend_id = fa.friend_id)
LOOP
IF (j.moved_out IS NULL OR
j.moved_out >= SYSDATE) THEN -- current resident.
IF v_curr_resident IS NULL
THEN
-- because the
variable is null, we know this is the first current resident for
this address.
v_curr_resident :=
j.first_name||' '||j.last_name;
ELSE
-- this isn't the
first current resident; concatenate so we don't overwrite the
previous name.
v_curr_resident :=
v_curr_resident||CHR(10)||CHR(9)||j.first_name||' '||j.last_name;
-- chr(10) is a line break. chr(9) is a tab.
END IF;
ELSE -- past residents
IF v_past_resident IS NULL
THEN
-- because the
variable is null, we know this is the first current resident for
this address.
v_past_resident :=
j.first_name||' '||j.last_name;
ELSE
-- this isn't the
first past resident; concatenate so we don't overwrite the
previous name.
v_past_resident :=
v_past_resident||CHR(10)||CHR(9)||j.first_name||' '||j.last_name;
END IF;
END IF;
END LOOP;