Search code examples
postgresqlplpgsqlpostgresql-9.3

Get the tables referenced by a view view using a function


I want to get tables referenced by a view and display them.

I have two tables: test1 and test2

I've created a view, which references these tables

CREATE VIEW First_View 
AS 
   SELECT * FROM test1 
UNION 
   SELECT * FROM test2;

I have created one table which contains the view details like view id and view name as shown below:

CREATE TABLE View_Details
(
view_id int,
view_name varchar
);

and inserted a record into it.

INSERT INTO view_details values(1,'First_View');

Now I am creating a function with one parameter v_id that is view_id and want to get all tables, which are referenced by the view_namt.

I'm doing this, but I'm getting nothing in Messages:

CREATE OR REPLACE FUNCTION For_testing(v_id INT)
RETURNS VOID AS
$$
Declare
    var varchar;
    v_name varchar;
BEGIN
    SELECT view_name INTO v_name from view_details where view_id = v_id;

    FOR var IN SELECT Table_NAME from INFORMATION_SCHEMA.VIEW_TABLE_USAGE
                        WHERE View_Name = v_name LOOP
    RAISE INFO '%',VAR;

    END LOOP;
END;
$$
language plpgsql;

Call Function:

SELECT for_testing(1);

Solution

  • try SELECT lower(view_name) INTO v_name from view_details where view_id = v_id; because it should be in double quotes to be First_View... I mean dictionary will change First_View to lower(First_View) if you dont use "First_View" when create a view...