Matt
Matt

Reputation: 2843

PLSQL select statement with variable help

Hello i am trying to do this simple statement but i want to add a variable that comes from a select. Here is what i have.

 userEmail varChar(50) := SELECT user_id FROM users WHERE email = 'email@email.com';
        SELECT * 
        FROM iphone_alerts
        WHERE user_id =  userEmail
        AND date_added = (SELECT MAX(date_added) FROM iphone_alerts WHERE user_id = userEmail  

Do i need to use something along the lines of Declare and Begins? I am new to the sql stuff and am having trouble finding answers.

Upvotes: 2

Views: 13550

Answers (3)

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181460

You need:

declare
    userEmail varchar2(200);
begin
    select user_id into userEmail
      from users
     where email = 'email@email.com';

    -- you will need a cursor to itare these results
    select * 
      from iphone_alerts
     where user_id =  userEmail
       and date_added = (select max(date_added) from iphone_alerts WHERE user_id);

end;

Edit after comment:

If select should return only ONE row, you don't need a cursor, but you need an into clause to store each retrieved value into a variable. Something like:

declare
    userEmail varchar2(200);
    v_field1 number; 
    v_field2 date;
    v_field3 varchar2(200);
begin
    select user_id into userEmail
      from users
     where email = 'email@email.com';

    -- you will need a cursor to itare these results
    select field1, field2, field3
      into v_field1, v_field2, v_field3
      from iphone_alerts
     where user_id =  userEmail
       and date_added = (select max(date_added) from iphone_alerts WHERE user_id);

end;

Upvotes: 4

Justin Cave
Justin Cave

Reputation: 231851

If you want to do this in SQL, you'd want something like

SELECT alerts.*
  FROM iphone_alerts alerts,
       users 
 WHERE alerts.user_id = users.user_id
   AND users.email = 'email@email.com'
   AND alerts.date_added = (SELECT MAX(date_added)
                              FROM iphone_alerts alerts2
                             WHERE alerts2.user_id = user.user_id)

Probably more efficient would be something like this that lets us hit the IPHONE_ALERTS table just once.

SELECT <<list of columns in IPHONE_ALERTS>>
  FROM (
    SELECT alerts.*,
           RANK() OVER (PARTITION BY alerts.user_id ORDER BY date_added DESC) rnk
      FROM iphone_alerts alerts,
           users 
     WHERE alerts.user_id = users.user_id
       AND users.email = 'email@email.com'
  )
 WHERE rnk = 1

Upvotes: 2

I'm not sure what you're trying to do, but I think you might need select into

declare 
    V_userID varChar(50) ;
begin
    /*This will store the value of the user_id field into the v_userID variable.*/
    SELECT user_id into v_userID FROM users WHERE email = 'email@email.com';
end;

http://download.oracle.com/docs/cd/B13789_01/appdev.101/b10807/13_elems045.htm

Upvotes: 0

Related Questions