Store Intelligence is a partner whose technological know-how and business expertise will allow you to grow your business.
Store Intelligence is a partner whose technological know-how and business expertise will allow you to grow your business.
postgresql function return setof record
If you want to return an existing record type, you need to make a dummy type to hold the output type, for example: Here we are defining a new type named holder which is a composite type of an integer named departmentid and a bigint named totalsalary. There seems to be some limitation with plpgsql that prevents you from using a set-valued function in the SELECT list of a query. Note that for the return next we are not returning the record r, but instead are returning just the departmentid because this function returns a set of integers. quote_literal() was the solution. > But, I get the following error:"ERROR: a column definition list is required > for functions returning "record" SQL state: 42601". Its a great HELP!!! Here we're figuring out the total salary plus the overhead and updating the record appropriately. SRFs can return either a rowtype as defined by an existing table or a generic record type. PostgreSQL's™ stored functions can return results in two different ways. The table would have 3 columns and an unknown number of rows. [Maybe: SELECT * FROM c_fcn() AS (a int, b text);]. Do you now a better way to create the type of the result type of the function. The return type of the function is setof employee, meaning it is going to return a rowset of employee rows. 2003/05/27 11:31 EST (via web): 2003/05/28 11:34 EST (via web): I agree This document should be in PostGre documentation. I am using postgreSQL version 7.2.2 Writing a function that returned the most current row for any given entry point was a little tricky as nothing mentioned recursion that I saw. Assignment of a yet-unknown column with the hstore operator #=. quote_literal() was the solution. In that case, you can return a setof record. GREAT!!! It returns a rowset of rows defined by the type holder (int, int8). The return next statement adds a row to the returned table of the function.. CREATE OR REPLACE FUNCTION wordFrequency(maxTokens INTEGER) RETURNS SETOF RECORD AS $$ BEGIN SELECT text, count(*), 100 / maxTokens * count(*) FROM ( SELECT text FROM token WHERE chartype = 'ALPHABETIC' LIMIT maxTokens ) as tokens GROUP BY text ORDER BY count DESC END $$ LANGUAGE plpgsql; I get a list of obvious numbers. That might be ok. 2003/04/17 03:39 EST (via web): I tried building the string as SELECT baz_number FROM baz_table WHERE customer_id = ' || cust_id || ' - no dice. Thank You. Turns out selecting into r and calling next fixed that. In this example, we created the get_film(varchar,int) that accepts two parameters:. We're going to work with a very simple set of tables and data and functions written in SQL and PL/pgSQL. Related (you linked to that one yourself): Refactor a PL/pgSQL function to return the output of various SELECT queries; FOR-IN-EXECUTE to loop over a dynamic query. Re: return setof record from function with dynamic query at 2002-12-18 15:21:10 from Stephan Szabo Re: return setof record from function with dynamic query at 2002-12-18 15:32:29 from Masaru Sugawara Browse pgsql-general by date justinc, 2003/01/28 16:35 EST (via web): So far, the composite type returning functions only work if you're certain that you're returning a type that is made up of the same types as the one the function is declared to return. Use the drop function statement with the cascade option to drop a function and its dependent objects and objects that depends on those objects, and so on. An SRF can be used in place of a table or subselect in the FROM clause of a query. SETOF anyelement - get_call_result_type; set returning function with variable argument - possible? The function may return either a refcursor value or a SETOF some datatype. ASSIGN to row variable. Incorrect: select sr_func(arg1, arg2, ...); Correct: select * from sr_func(arg1, arg2, ...); 2003/03/29 13:52 EST (via web): The key point here is that you must write RETURNS SETOF record to indicate that the function returns multiple rows instead of just one. Does someone know what is wrong with the example? This limitation may be removed in a future version. However, that does give you a workaround: you can call the PL/pgSQL function *from* an SQL function. Thanks, this helped quite a bit. I am not aware of how to do this in PLPGSQL. al.) 2003/11/03 00:16 EST (via web): > Then I changed it to return SETOF RECORD, in order to be able to return > dataset with varying number of columns. I've tried the following using PostgreSQL 9.2: CREATE OR REPLACE FUNCTION test() RETURNS SETOF record Which gives me the following error: ERROR: a column definition list is required for functions returning "record" I've also tried: CREATE OR REPLACE FUNCTION test() RETURNS table () Question about functions that return a set of records Group by clause creating "ERROR: wrong record type supplied in RETURN NEXT" (version 8.1.11 -- grr...) Function Returning SETOF RECORD: Trouble With Char Type (2 replies) I am porting some Oracle code to PLPGSQL and am having a problem with functions that return SETOF datatype. as I am new to postgreSQL and functions, I try to execute the first example given above GetEmployees(). A PL/pgSQL function can also do additional operations on the records or only queue up only some records. The rows that it returns are defined by the group by query in its body. Here it is again. al.) Perfect! These functions are used in the same fashion as the first function. What I want is to creat a function that will manage these tables when an event occures. 2003/02/27 11:27 EST (via web): On Wed, 18 Dec 2002, Toby Tremayne wrote: > -----BEGIN PGP SIGNED MESSAGE-----> Hash: MD5>> Hi all,>> I've been beating my head against the desk for days on this, and> I've been completely unable to find docs on it. This tutorial must become part of Postgresql Function Documentation, with more examples in many other languages than SQL and PL/PGSQL such as Python, Perl, C, etc... 2003/04/24 16:44 EST (via web): The main body does a loop over the group by query stated setting r to each row in sequence. But If I give a SELECT * from GetEmployees(); Here we've passed in Department as the argument which means that we expect to get rows in the general form of Department records which is an integer followed by a text string, so we tell PostgreSQL that the alias for the result should be called dept and that it is made up of an integer named deptid and a text named deptname. I have a function returning setof record. > ERROR: A column definition list is required for functions returning RECORD. The p_pattern is used to search for films. The following simplified example shows what I'm talking about Using OUT and INOUT function arguments. It give me this error: WARNING: Error occurred while executing PL/pgSQL function getnum WARNING: line 8 at return next ERROR: Set-valued function called in context that cannot accept a set Is there any one can tell me what wrong with it??? From: To: pgsql-sql(at)postgresql(dot)org: Subject: plpgsql function returning SETOF RECORD Question: Date: 2004-02-23 13:21:32 This does not cause the function to return. The following is what I did. Add your comments here... 2003/04/17 05:53 EST (via web): Notice that if we were to carry out this logic without stored functions we would have to make several round trips to the server to achieve our goal. old records-> new records. I need a Postgres function to return a virtual table (like in Oracle) with custom content. Add your comments here... Imagine this: CREATE OR REPLACE FUNCTION 'public'. A caviat: if you are dealing with a WHERE clause in the EXECUTE SELECT, you may want to quote_literal() your string variables (if they are being passed in). This very simple function simply returns all the rows from employee. For example: CREATE FUNCTION public.sp_get_baz_for_cust(bpchar) RETURNS SETOF bpchar AS ' DECLARE cust_id ALIAS FOR $1; baz_num CHAR( 15 ); selected_baz RECORD; BEGIN FOR selected_baz IN EXECUTE SELECT baz_number FROM baz_table WHERE customer_id = || quote_literal( cust_id ) LOOP RETURN NEXT selected_baz.ticket_number; END LOOP; RETURN; END; Without quote_literal(), the query tends to choke on special characters (like colons, dashes, et. 2003/03/14 18:39 EST (via web): Yes, I agree.. Let's do something very simple, a function that returns the numbers from 1 to an argument and those numbers doubled. Here is an example of my probem : something like DECLARE rec RECORD; BEGIN rec.$1 := 1; (...), 2004/05/22 09:02 AST (via web): Obtaining a ResultSet from a stored function. I run into this most often when creating complex pivot tables that do not use agrigates. The function makes a variable of the rowtype numtype and for each number from 1 to the passed argument assigns num and doublenum and then does return next r; in order to enqueue a row of output. First let's look at a simple SQL function that returns an existing table's rowtype. Want to edit, but don't see an edit button when logged in? Let's break down this function. Note that if you don't fill in all the values for the return type for each return next, old values will be used, so you have to manually null them. Consider a function with header: CREATE OR REPLACE FUNCTION dates_pkg.getbusinessdays(pstartdate timestamp … I assume in this that you already have some experience with writing functions in SQL and PL/pgSQL for PostgreSQL. I have a table called "events" and anoteher called "event_parameter" and some other tables that are also conected with these two. 2003/06/30 08:25 EST (via web): Functions returning setof record -- can I use a table type as my return type hint? It would be really nice if someone (other than me) with a bit of spare time would hit the "Edit this page" link at the top of this page and fix up the comments and properly line up the examples. If you call your set-returning function the wrong way (IOW the way you might normally call a function), you will get this error message: Set-valued function called in context that cannot accept a set. Thanks, 2005/08/02 10:54 GMT (via web): The PL/pgSQL function is a little more complicated, but let's go through it. 2003/10/24 17:31 EST (via web): #include function with multiple return values I just couldn't find the correct syntax on the internet. For example, if you wanted to get an idea of operating expenses for departments where the overhead is 75% for departments whose total salaries were greater than 70,000 and 50% otherwise and only wanted to return department ids for departments whose salaries plus overhead was greater than 100,000 you might write something like: Let's look at the differences between this and PLpgSQLDepartmentSales(). The name of a table it acts on is one of its input variables, and its output is a set of rows from that table. The body of the function is a very simple SQL statement to generate the output rows. I think it won't like spaces much either. 2003/11/03 00:12 EST (via web): firstname.lastname@example.org. 2003/04/01 18:21 EST (via web): [/QUOTE] That single predicate, "multiple output parameters", is creating the (useless?) If you come from a SQL Server or IBM DB2 background, the RETURNS TABLE construct is probably most familiar, but still … Add your comments here... 2005/07/11 16:59 GMT (via web): If you came here wondering how you can return multiple values from a function (like in Oracle PL/SQL): CREATE FUNCTION temp() RETURNS record DECLARE v_record RECORD; BEGIN select 1, 6, 8 into v_record; return v_record; END; Then you do: select * from temp() as (int4, int4, int4). Returning From a Function There are two commands available that allow you to return data from a … special case for a single column output. If you make a mistake, you'll get an error at creation time for SQL functions and at execute time for PL/pgSQL functions. I have a stored function in a postgresql databse, and I want to call it from my java program. 2005/03/13 14:59 GMT (via web): So, when we implemented support for table-valued functions, we only supported those that return a TABLE type, in jOOQ 3.5. jOOQ 3.6 will also support SETOF functions. Is there any way to get the n-th item in a record? Newbie: This article requires PostgreSQL version 7.3 or greater. As for status return, if there's an error (excepting a foreign key violation that is not yet checked - like deferred constraints) right now the statement will be ended so it won't get to the next statement in the function. 2003/06/26 04:31 EST (via web): > > I have a function returning setof record. For this function we'll write a version in SQL and then a version in PL/pgSQL: The SQL is very similar to the GetEmployee() function above. Let's make a function that returns all the rows of a table whose name you pass in as a parameter. When you use the function, you need to say something like: select * from func() as foo(col1 int, col2 varchar, ...); Since it's an arbitrary record type, it doesn't know what the types are, so you need to provide it at select time. In a prior article Use of Out and InOut Parameters we demonstrated how to use OUT parameters and INOUT parameters to return a set of records from a PostgreSQL function. My original problem is that the function takes one parameter of type regclass as input and returns a setof records (the row type of the corresponding input regclass). Next, we want to determine if the totalsalary is now greater than 100,000 and if so return it's identifier, so. Use drop function statement to remove a function. Im confuse about set returning function when read Documentation, but after surf www.postgresql.org , search, found this tutorial, Im glad ... Thx. Unfortunately, we overlooked the possibility of distinguishing between functions that return a TABLE (of a type) or a SETOF (a type) in PostgreSQL. It's pretty ugly and when I did the discussion at SFPUG it was pretty unanimous that it was a bad hack and pretty much the wrong way to go about solving the problem. [tablefunc.c does this, but for a ROWTYPE, not a RECORD] What would be the syntax for calling this? cases it must be done interatively): sszabo, 2003/05/15 19:18 EST (via web): We can do the same thing using a record type so that we do not need an outside type, however it is much more complicated and involves a bogus select. Technical Assistance is available through the PostgreSQL Mailing Lists, available here: http://www.postgresql.org/community/lists. Just a quick note for a problem I was having. Now, what about some samples of functions that return sets in C language? In the function body, we used a for loop staetment to process the query row by row.. Sorry, forgot the pre /pre around my code. For example: Without quote_literal(), the query tends to choke on special characters (like colons, dashes, et. > > > I have a plpgsql function that returns dataset. PostgreSQL 7.3 now supports a much more flexible system for writing set returning functions (SRFs) that when combined with some of the new function permission options allow a greater flexibility in setting up schemas. If there is only one output parameter, write that parameter's type instead of record. The function name above is “get_people ()” which returns an SETOF (a list of records) of type person. For the longest time I was stuck on getting 0 records back. 2003/04/24 14:52 EST (via web): In this case I cannot create a wrapper function since the return type is known only at the execution time, can't I? 2003/05/29 08:00 EST (via web): 2003/10/17 19:26 EST (via web): The SETOF modifier indicates that the function will return a set of items, rather than a single item. I have a function> (code below) that creates and executes a dynamic query. Sorry for the spooge in the last posting. Dynamic, using AS (name type, …) at call site : SETOF RECORD. In Oracle, the functions I'm porting return a TABLE of TYPE datatype, this TABLE being itself a named type. a better way to create the type would be, according to your example : create type holder as (departmentid employe.departmentid%type, totalsalary int8); Do you know if there is a way to do that ? The name of a table it acts > on is one of its input variables, and its output is a set of rows > from that table. Currently, functions returning sets can also be called in the select list of a query. create or replace function get_current_rec(numeric) returns setof rec as ' declare r rec%rowtype; begin for r in select a, b, c, d as total from table where key = $1 loop if r.replaced_by IS NULL THEN return next r; ELSE raise notice ''trying to fetch record for %'',r.replaced_by; select into r * from get_current_rec(r.replaced_by); return next r; end if; end loop; return; end ' language 'plpgsql'; then I get a ---> ERROR: parser: parse error at or near "(". The following simplified example shows what I'm talking about (I know this could be done with sub-selects, but in more complicated cases it must be done interatively): 2003/04/24 16:48 EST (via web): :), 2003/01/14 01:25 EST (via web): Does anyone have an example of a C function which returns a SETOF RECORD? In fact, it's a dammage to declare a type with explicit type when we already knows the type return by the function. RETURN NEXT var; SETOF