如何使用SQL语句测试表中是否存在列

CSh*_*ned 51 postgresql information-schema

在PostgreSQL中有一个简单的替代方法来生成Oracle中的这个语句吗?

select table_name from user_tab_columns
where table_name = myTable and column_name = myColumn;
Run Code Online (Sandbox Code Playgroud)

然后我测试查询是否返回任何内容以证明列存在.

我知道使用psql我可以单独找到这些,但这是在我编写的程序中生成结果以验证我的数据库表中存在请求的属性字段所必需的.

Ram*_*ngh 102

试试这个 :

SELECT column_name 
FROM information_schema.columns 
WHERE table_name='your_table' and column_name='your_column';
Run Code Online (Sandbox Code Playgroud)

  • @EvgenyIt显示在原始问题中. (3认同)
  • 这是一个*极其*脆弱的答案 - 例如,。如果名为“your_table”的表出现在“search_path”上方的“schema”中。我的 PostGIS 数据库有每月模式,每个模式都有相同的表名;使用这个答案,“vicmap201208.address”将在“vicmap201910.address”之前找到,因为“vicmap201208”出现在“search_path”上的“vicmap201910”之前(有充分的理由,我不想仅仅为了使错误的答案起作用而进行更改) )。[碰巧,列名在模式中是不变的:这不是重点] (2认同)

jua*_*aza 28

接受的答案是正确的,但缺少架构和更好的输出(真/假):

SELECT EXISTS (SELECT 1 
FROM information_schema.columns 
WHERE table_schema='my_schema' AND table_name='my_table' AND column_name='my_column');
Run Code Online (Sandbox Code Playgroud)

  • 或者只是“从 information_schema.columns WHERE ... 中选择存在的 true”; (2认同)

Erw*_*ter 15

使用PostgreSQL的对象标识符类型更简单(并且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)
Run Code Online (Sandbox Code Playgroud)

阅读手册中列重要性.

如果要构建动态SQL并且您的列名作为参数提供,则可能需要使用quote_ident()以避免SQL注入:

...
AND    attname = quote_ident('myColumn');
Run Code Online (Sandbox Code Playgroud)

适用于以外的表格search_path:

...
WHERE  attrelid = 'mySchema.myTable'::regclass
...
Run Code Online (Sandbox Code Playgroud)


小智 5

与 Oracle 不同,PostgreSQL 支持 ANSI 标准INFORMATION_SCHEMA视图。

Oracle的user_tab_columns对应的标准视图是information_schema.columns

http://www.postgresql.org/docs/current/static/infoschema-columns.html