I am trying to combine the following two sql statements in my application code into a function in postgresql, but I'm having some trouble. Here are the two sql queries I'd like to combine:
UPDATE userrange f
SET UsedYesNo = true, user_id=user_id, updateddatetime=now()
WHERE f.uservalue IN(
SELECT a.uservalue FROM userrange a WHERE UsedYesNo=false Order By id ASC Limit 1)
RETURNING a.uservalue;
The results from the above statement are used in this query:
INSERT INTO widget
VALUES(DEFAULT, uservalue, 'test','123456778',1,"testservername", now(), Null)
So far, I've built function that just does the first update statement, like so:
CREATE or REPlACE FUNCTION create_widget(IN user_id integer, IN password character varying DEFAULT NULL::character varying)
RETURNS TABLE(uservalue integer) AS
$BODY$
BEGIN
RETURN QUERY
UPDATE userrange f SET UsedYesNo = true, user_id=user_id, updateddatetime=now()
WHERE f.uservalue IN(
SELECT a.uservalue FROM userrange a WHERE UsedYesNo=false Order By id ASC Limit 1)
RETURNING a.uservalue;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
It compiles but when I execute it, it fails with the error:
ERROR: missing FROM-clause entry for table "a" LINE 4: RETURNING a.uservalue
I'm just googling this error to see how I can fix it... but could I just create a variable called uservalue in a DECLARE section and use it in the secondary query? Or can i combine the sql into one
thanks.