gpt4 book ai didi

PostgreSQL 如何检查表是否存在?

转载 作者:行者123 更新时间:2023-11-29 14:08:20 32 4
gpt4 key购买 nike

这是我们如何在 MSSQL 中检查表是否存在:

IF OBJECT_ID(N'public."TABLE_NAME"', N'U') IS NOT NULL
select 1 as 'column'
else
select 0 as 'column';

将结果存储在变量“列”中

我怎样才能在 PostgreSQL 中做同样的事情?我想为各自的结果返回 1 或 0。

最佳答案

使用带有 EXISTS 运算符的 SELECT 检查,例如information_schema.tables:

select exists (select *
from information_schema.tables
where table_name = 'table_name'
and table_schema = 'public') as table_exists;

如果您不能(或不愿)处理正确的 bool 值,只需将结果转换为数字即可(但我不知道为什么这样更好):

select exists (select *
from information_schema.tables
where table_name = 'table_name'
and table_schema = 'public')::int as "column";

请注意,column 是保留关键字,因此您需要使用双引号将其引用。

关于PostgreSQL 如何检查表是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56769683/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com