SELECT TRUE FROM pg_attribute
WHERE attrelid = (
SELECT c.oid
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE
n.nspname = CURRENT_SCHEMA()
AND c.relname = 'YOURTABLENAME'
)
AND attname = 'YOURCOLUMNNAME'
AND NOT attisdropped
AND attnum > 0
3
接受的答案是正确的,但缺少架构和更好的输出(真/假):
SELECT EXISTS (SELECT 1
FROM information_schema.columns
WHERE table_schema='my_schema' AND table_name='my_table' AND column_name='my_column');
SELECT TRUE
FROM pg_attribute
WHERE attrelid = 'myTable'::regclass -- cast to a registered class (table)
AND attname = 'myColumn'
AND NOT attisdropped -- exclude dropped (dead) columns
-- AND attnum > 0 -- exclude system columns (you may or may not want this)
6 回答
试试这个 :
以下是Erwin Brandstetter答案的类似变体 . 在这里我们检查模式,以防我们在不同的模式中有类似的表 .
接受的答案是正确的,但缺少架构和更好的输出(真/假):
使用PostgreSQL的object identifier types更简单(并且SQLi安全):
阅读significance of the columns in the manual .
如果要构建动态SQL并且您的列名作为参数提供,则可能需要使用quote_ident()来避免SQL注入:
适用于
search_path
之外的表格:与Oracle不同,PostgreSQL支持ANSI标准
INFORMATION_SCHEMA
视图 .Oracle的user_tab_columns的相应标准视图是
information_schema.columns
http://www.postgresql.org/docs/current/static/infoschema-columns.html
当然,用适当的值替换 YOURTABLENAME 和 YOURCOLUMNNAME . 如果返回一行,则存在具有该名称的列,否则不存在 .