Question

Here i need to select a column name by using function(stored procedure) which is present in other database table using PostgreSQL.

I have sql server query as shown below.

Example:

create procedure sp_testing 
as 
       if not exists ( select ssn from testdb..testtable) /*ssn is the column-name of testtable which exists in testdb database */
       ...

Q: Can i do the same in PostgreSQL?

Was it helpful?

Solution

Your question is not very clear, but if you want to know if a column by a certain name exists in a table by a certain name in a remote PostgreSQL database, then you should first set up a foreign data wrapper, which is a multi-stage process. Then to test the existence of a certain column in a table you need to formulate a query that conforms to the standards of the particular DBMS that you are connecting to. Use the remote information_schema.tables table for optimal compatibility (which is here specified as remote_tables which you must have defined with a prior CREATE FOREIGN TABLE command):

CREATE FUNCTION sp_testing () AS $$
BEGIN
  PERFORM *
  FROM remote_tables
  WHERE table_name = 'testtable'
  AND column_name = 'ssn';

  IF NOT FOUND THEN
     ...
  END IF;
END;
$$ LANGUAGE plpgsql;

If you want to connect to another type of DBMS, you need to write some custom function in f.i. C or perl and then call that from within a PostgreSQL function on your local machine. The test on the column is then best done inside the function which should therefore take connection parameters, table name and column name as parameters, and return a boolean to inform the result.

Before you start testing this, make sure that you read all the documentation on connecting to remote servers and learning PL/pgSQL first would also be a nice gesture to demonstrate your own efforts before you ask for help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top