如何使用SQL语句测试表中是否存在列
PostgreSQL中是否存在Oracle中生成的此语句的简单替代方法?如何使用SQL语句测试表中是否存在列
select table_name from user_tab_columns
where table_name = myTable and column_name = myColumn;
我然后测试查询是否返回任何东西,以证明列存在。
我知道,使用psql我可以单独找到这些,但这是在编写的程序中产生结果所必需的,用于验证我的数据库表中存在请求的属性字段。
试试这个:
SELECT column_name
FROM information_schema.columns
WHERE table_name='your_table' and column_name='your_column';
SELECT attname
FROM pg_attribute
WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'YOURTABLENAME')
AND attname = 'YOURCOLUMNNAME';
当然,更换YOURTABLENAME和YOURCOLUMNNAME用适当的值。如果返回一行,则存在具有该名称的列,否则不存在。
感谢您的回复。虽然你的例子工作正常,但我选择接受Ramandeeps答案,因为它的简单性和它似乎是我的问题更直接的选择。 – CSharpened 2012-04-03 10:14:38
与Oracle不同,PostgreSQL支持ANSI标准INFORMATION_SCHEMA
的视图。
Oracle的USER_TAB_COLUMNS相应的标准视图是information_schema.columns
http://www.postgresql.org/docs/current/static/infoschema-columns.html
这与PostgreSQL的object identifier types简单(SQLI安全):
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)
阅读关于significance of the columns in the manual。
如果你正在构建的动态SQL和您的列名提供的参数,你可能需要使用quote_ident()
避免SQL注入:在search_path
外
...
AND attname = quote_ident('myColumn');
Works的表,太:
...
WHERE attrelid = 'mySchema.myTable'::regclass
...
接受的答案是正确的,但缺少模式和更好的输出(True/False):
SELECT EXISTS (SELECT 1
FROM information_schema.columns
WHERE table_schema='my_schema' AND table_name='my_table' AND column_name='my_column');
这是Erwin Brandstetter的一个类似的变体答案。 这里我们也检查模式,以防我们在不同模式中有类似的表。
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
谢谢。被接受为答案,因为它直接替代了我在Oracle中做的事情。 – CSharpened 2012-04-03 10:13:43
在MySQL上的工作方式是相同的,这很好 – Evgeny 2013-04-18 19:40:33
@CSharpened Oracle的查询是什么? – Evgeny 2013-04-18 19:41:08