这是我们可以检查MSSQL中表是否存在的方式:
IF OBJECT_ID(N'public."TABLE_NAME"', N'U') IS NOT NULL
select 1 as 'column'
else
select 0 as 'column';
将结果存储在变量“ column”中
我如何在PostgreSQL中做同样的事情?我想分别返回1或0。
答案 0 :(得分:2)
将SELECT与EXISTS运算符一起使用,例如检查information_schema.tables
:
select exists (select *
from information_schema.tables
where table_name = 'table_name'
and table_schema = 'public') as table_exists;
如果您不能(或不会)处理正确的布尔值,只需将结果转换为数字即可(但我不知道为什么这样做会更好):
select exists (select *
from information_schema.tables
where table_name = 'table_name'
and table_schema = 'public')::int as "column";
请注意,column
是保留关键字,因此您需要使用双引号将其引起来。
答案 1 :(得分:2)
检查表是否存在使用视图pg_tables的列
$ClientID = "a6ec906d-xxxxx00dd3" #ApplicationID
$ClientSecret = "XwaNxxxxx/44" #key from Application
$tennantid = "bb58xxxxxxd6c65"
$objectid = "ca8xxxef66db07c0" #object id of the application
$TokenEndpoint = {https://login.windows.net/{0}/oauth2/token} -f $tennantid
$ARMResource = "https://graph.windows.net/";
$Body = @{
'resource'= $ARMResource
'client_id' = $ClientID
'grant_type' = 'client_credentials'
'client_secret' = $ClientSecret
}
$params = @{
ContentType = 'application/x-www-form-urlencoded'
Headers = @{'accept'='application/json'}
Body = $Body
Method = 'Post'
URI = $TokenEndpoint
}
$token = Invoke-RestMethod @params
$accesstoken = $token.access_token
$url = {https://graph.windows.net/{0}/applications/{1}?api-version=1.6} -f $tennantid,$objectid
$header = @{
'Authorization' = 'Bearer ' + $accesstoken
'Content-Type' = 'application/json'
}
$json = @{
oauth2AllowIdTokenImplicitFlow = 'false' #or true
}
$body = $json | ConvertTo-Json
Invoke-RestMethod –Uri $url –Headers $header -Body $body –Method PATCH
对于我的SQL,使用INFORMATION_SCHEMA.COLUMNS
IF EXISTS ( SELECT attname
FROM pg_attribute
WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'YOURTABLENAME')
AND attname = 'YOURCOLUMNNAME')
THEN
-- do something
END IF;