1

I need some help with defining a Function in postgreSQL:

here are my table definitions:

CREATE TABLE venue (
   id INTEGER DEFAULT NEXTVAL('venue_id_seq')
 , building_code building_code
 , floorNo int
 , roomNo int
 , width int
 , length int
);

I need to create a function related to that table that gives me the Floor area.Here is what I have so far:

CREATE FUNCTION floorArea(id int) RETURNS int AS '
SELECT  venue.width * venue.length AS result ;
' LANGUAGE SQL;

I don't know how to possibly make variables etc.
I want something along the lines of:

var width=  Select width from venue where id=$1;
var length=  Select length from venue where id=$1;
return width * length;

2 Answers 2

2

There are no variables inside an SQL function. You need to use PL/pgSQL or another procedural language for that.

With plpgsql it could look like this:

CREATE FUNCTION floor_area(_id int)
  RETURNS int AS
$func$
DECLARE
   _width   int;
   _length  int;
BEGIN

SELECT INTO _width, _length
             width,  length
FROM   venue
WHERE  id = _id;

RETURN width * length;

END
$func$ LANGUAGE plpgsql;

Consider what I wrote about parameter names in my other answer.

But a simple task like this should be solved with plain SQL without variables like @Roman already supplied.

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

Comments

1

I think you can do something like

CREATE FUNCTION floorArea(idp int)
RETURNS int
as
$$
    select width * length from venue as v where v.id = idp
$$ LANGUAGE SQL;

sql fiddle demo

2 Comments

I make it a habit to prefix parameter names with _, like _id, to avoid conflicts altogether. It also helps to quickly identify parameter names in the code. Also, I also advise against unquoted CamelCase identifiers like floorArea. It leads to confusion easily. There have been several desperate questions here, stemming from that.
I'm working with SQL Server at my job, PostgreSQL only fo fun (although I'd like to work with PostgreSQL), so we always have @ before parameters. Anyway, thanks for tip

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.