stored procedures in postgresql - postgresql

I want to know WHERE to write stored procedures in PostgreSQL?
I mean not how to write but the very basic thing where to write, where to go if I want to write one?
Is it written just like query or in some different sort of file?
I am fairly new to postgresql
So please explain as much as possible

Just use any text editor to create a (SQL) file containing the necessary CREATE FUNCTION statement.
Then run that file using psql.
As an alternative you can use a GUI tool like pgAdmin or something similar (Squirrel, DbVisualizer, SQL Workbench/J, ...) where you have the editor "built-in"
You can directly run the statement that you edit against the database.

Use the CREATE FUNCTION... command in whatever your prefered PSQL manager is.
Something like this (psuedo SQL):
CREATE OR REPLACE FUNCTION
MyProc(text, text)
RETURNS
void
AS
$delimiter$
INSERT INTO MyTable (text_val_1, text_val_2)
VALUES ($1, $2);
$delimiter$
LANGUAGE SQL;
More info can be found here:
http://www.day32.com/MySQL/Meetup/Presentations/postgresql_stored_procedures.pdf

You need to open pgAdmin application which you need to install if you do not have it.
Then you need click on this button as I have marked and then a query editor will appear at right side. You will write your query or stored procedure or functions here in this query editor.
See the screenshot attached :

Related

Command to read a file and execute script with psql

I am using PostgreSQL 9.0.3. I have an Excel spreadsheet with lots of data to load into couple of tables in Windows OS.
I have written the script to get the data from input file and Insert into some 15 tables. This can't be done with COPY or Import. I named the input file as DATALD.
I find out the psql command -d to point the db and -f for the script sql. But I need to know the commands how to feed the input file along with the script so that the data gets inserted into the tables..
For example this is what I have done:
begin
for emp in (select distinct w_name from DATALD where w_name <> 'w_name')
--insert in a loop
INSERT INTO tblemployer( id_employer, employer_name,date_created, created_by)
VALUES (employer_id,emp.w_name,now(),'SYSTEM1');
Can someone please help?
For an SQL script you must ..
either have the data inlined in your script (in the same file).
or you need to utilize COPY to import the data into Postgres.
I suppose you use a temporary staging table, since the format doesn't seem to fit the target tables. Code example:
How to bulk insert only new rows in PostreSQL
There are other options like pg_read_file(). But:
Use of these functions is restricted to superusers.
Intended for special purposes.

What is the purpose of pgScript in PostgreSQL?

I have failed to understand the need for pgScript, which could be executed using pgAdmin tool. When it should be used? What it can do that plpgSQL cannot do? What is equivalent of it in Microsoft SQL Server?
pgScript is a client-side scripting language, while pl/PgSQL runs on the server. This means they have entirely different use cases. For example, PgScript can manage transaction status while pl/PgSQL cannot, but pl/Pgsql can be used to extend the language of SQL while pgScript cannot do that.
Additionally it means the two will handle many other things quite differently ranging from query plans to dynamic SQL, and while pgScript requires round trips between queries pl/Pgsql does not.
One use for pgScript is to define variables and use them later in your SQLs.
For example, you could do something like this:
declare #mytbl, #maxid;
set #mytbl = 'sometable';
set #maxid = 2500;
set #res = select count(*) from #mytbl where id <= #maxid;
print #res;
This approach is to just have any variables you want to change at the top of your script, rather than those getting buried deep inside complex SQL queries.
Of course, pgScript is a feature available only inside PgAdmin III client like #{Craig Ringer} mentioned in his comment.
I used DDL script generator from Toad Data Modeler.
I ran the script using normal query execution in PgAdmin-III but it kept giving me error:
"ERROR: relation "user" already exists SQL state: 42P07".
I ran Execute pgScript in PgAdmin-III and it worked fine.

How do I store a set of queries inside PostgreSQL so I can easily run it again?

I want to save a set of queries (multiple SQL updates) as a single element that I can execute using pgAdmin3 (PostgreSQL 9.1).
I know that I can save single SELECTS as views but how about multiple UPDATE queries?
Example:
BEGIN;
UPDATE ...;
UPDATE ...;
COMMIT;
Update: What I looking for is a step-by-step guide of adding a stored procedure using the GUI, not running a SQL query that creates it.
So far, I encountered two problems with "New function...": the return type is required and found that NULL is not acceptable, so tried integer. Also, set the type to SQL but I don't know what exactly to write inside the SQL tab, whatever I try the OK button is still disabled and the statusbar says: Please enter function source code.
Do you know or did you try stored procedure (well, stored-procedure-like functions) ?
http://www.postgresql.org/docs/9.1/interactive/plpgsql-structure.html
To call it
select <name of function>(<param1>, <param2>) as result;
Here is the missing guide for a basic SQL stored procedure, one that does return 1.
right click on Functions and choose New Function...
complete name as my_procedure, return type as integer, language as sql
select Definition tab and write SELECT 1;
done
It would be nice to know if you can create queries that are returning nothing.

PostgreSQL: How do I export a function definition to SQL

I have a function (stored procedure) defined in a database that I would like to edit.
I think one way of doing this is to dump the function definition to a SQL file, edit the SQL file, then replace the definition in the database with the edited version.
Is it possible to do this (dump the definition to a SQL file)?
What I have been doing in the past is to use psql to connect to the database, run /df+ function, copy the output to a text file, massage the text so it looks like a function declaration, but this is time consuming and I'm wondering if there is a sleeker way of doing it.
I am using PostgreSQL 9.1 if it matters.
EDIT:
I accepted Mike Buland's answer because he provided the correct answer in his comment, which was to run \ef function in psql.
This is actually listed in a previous question:
SELECT proname, prosrc
FROM pg_catalog.pg_namespace n
JOIN pg_catalog.pg_proc p
ON pronamespace = n.oid
WHERE nspname = 'public';
List stored functions that reference a table in PostgreSQL
You should be able to use this on the command line or with a client to read the current text of the proc and do anything you'd like with it :)
I hope that helps
You would also need the function arguments:
SELECT p.proname
, pg_catalog.pg_get_function_arguments(p.oid) as params
, p.prosrc
FROM pg_catalog.pg_proc p
WHERE oid = 'myschema.myfunc'::regproc;
Or, to make it unambiguous for functions with parameters:
WHERE oid = 'myschema.myfunc(text)'::regprocedure;
Or you can use pgAdmin to do what you describe a lot more comfortably. It displays the complete SQL script to recreate objects and has an option to copy that to the the edit window automatically. Edit and execute.
I think you need to take a step back and see the root issue here. Which is you're not using version control to version your files (database objects). There are plenty of free ones, Git and Mercurial to name a few. So use psql or the query Mike provided to dump the structure out and put them in version control. Going forward check out from version control and make edits there. You should be deploying code from this version control system to the database server. It is also useful to reconcile that the code you have in version control matches the code in the database in a automated and on a regular basis. In theory though if a strict process is in place code that isn't checked into source control should never make it to the database and you don't ever have to wonder if source control matches what the database has. However I don't trust that people with admin access won't abuse their privilege so I put steps in place to check this. If someone is found to be abusing their privileges that can be dealt with in other ways.

Execute Stored Process with pass in SQL query from another table?

Currently my development environment is using SQL server express 2008 r2 and VS2010 for my project development.
My question is like this by providing a scenario:
Development goal:
I develop window services something like data mining or data warehousing using .net C#.
That meant I have a two or more database involved.
my senario is like this:
I have a database with a table call SQL_Stored inside provided with a coloum name QueryToExec.
I first idea that get on my mind is written a stored procedure and i tried to came out a stored procedure name Extract_Sources with two parameter passed in thats ID and TableName.
My first step is to select out the sql need to be execute from table SQL_Stored. I tried to get the SQL by using a simple select statement such as:
Select Download_Sql As Query From SQL_Stored
Where ID=#ID AND TableName=#TableName
Is that possible to get the result or is there another way to do so?
My Second step is to excecute the Sql that i get from SQL_Stored Table.Is possible to
to execute the query that select on the following process of this particular stored proc?
Need to create a variable to store the sql ?
Thank you,Appreciate for you all help.Please don't hesitate to voice out my error or mistake because I can learn from it. Thank you.
PS_1:I am sorry for my poor English.
PS_2:I am new to stored procedure.
LiangCk
Try this:
DECLARE #download_sql VARCHAR(MAX)
Select
#download_sql = Download_Sql
From
SQL_Stored
Where
AreaID = #AreaID
AND TableName = #TableName
EXEC (#download_sql)