3


I'm creating a stored procedure that changes email address, but I keep getting an error.

ERROR: syntax error at or near "UPDATE"

CREATE FUNCTION change(
IN oldAddr VARCHAR(50),
IN newAddr VARCHAR(50)
) AS
UPDATE accounts
SET a_email = newAddr
WHERE a_email = oldAddr;

I copied this from the textbook, but I don't think it works on PostgreSQL.
Please teach me how to correct it! Thank you!

CREATE TABLE accounts (
a_id int NOT NULL PRIMARY KEY,
a_first_name varchar(25) NOT NULL,
a_last_name varchar(25) NOT NULL,
a_email varchar(50) NOT NULL,
a_password varchar(16) NOT NULL
);

1 Answer 1

7

Try it this way

CREATE OR REPLACE FUNCTION change_account_email(
  IN oldAddr VARCHAR(50),
  IN newAddr VARCHAR(50))
RETURNS INTEGER AS 
$$
DECLARE
  rcount INTEGER DEFAULT 0;
BEGIN
  UPDATE accounts
     SET a_email = newAddr
   WHERE a_email = oldAddr;
   GET DIAGNOSTICS rcount = ROW_COUNT;
   RETURN rcount;
END;
$$
LANGUAGE plpgsql;

Sample usage:

SELECT change_account_email('[email protected]', '[email protected]');

Let's try it:

# INSERT INTO accounts VALUES(1, 'John', 'Doe', '[email protected]', '*********');
INSERT 0 1

# SELECT change_account_email('[email protected]', '[email protected]');
 change_account_email 
----------------------
                    1
(1 row)

# SELECT * FROM accounts;
 a_id | a_first_name | a_last_name |     a_email     | a_password 
------+--------------+-------------+-----------------+------------
    1 | John         | Doe         | [email protected] | *********
(1 row)

Here is SQLFiddle demo

Sign up to request clarification or add additional context in comments.

1 Comment

Okay. Sorry, I am new here. Thank you again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.