简体   繁体   中英

Perform query using tables and columns from information_schema

I'm trying to using information_schema.columns to find all of the columns in my database that has a geometry type and then check the SRID for the data in those columns.

I can do this with multiple queries where I first find the table names and column names

SELECT table_name, column_name
FROM information_schema.columns
WHERE udt_name = 'geometry';

and then (manually)

SELECT ST_SRID(column_name)
FROM table_name;

for each entry.

Does anyone how to streamline this into a single query?

Table names can't be variable; Postgres needs to be able to come up with an execution plan before it knows the parameter values. So you can't do this in a simple SQL statement.

Instead, you need to construct a dynamic query string using a procedural language like PL/pgSQL:

CREATE FUNCTION SRIDs() RETURNS TABLE (
  tablename TEXT,
  columnname TEXT,
  srid INTEGER
) AS $$
BEGIN
  FOR tablename, columnname IN (
    SELECT table_name, column_name
    FROM information_schema.columns
    WHERE udt_name = 'geometry'
  )
  LOOP
    EXECUTE format(
      'SELECT ST_SRID(%s) FROM %s',
      columnname, tablename
    ) INTO srid;
    RETURN NEXT;
  END LOOP;
END
$$
LANGUAGE plpgsql;

SELECT * FROM SRIDs();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM