【问题标题】:How to declare a variable and use it in an if statement in Postgres如何声明一个变量并在 Postgres 的 if 语句中使用它
【发布时间】:2019-12-24 02:24:32
【问题描述】:

我想根据查询结果创建一个变量,然后在 IF 语句中使用它。到目前为止我有这个:

with variable as (select "Id" from public.tableName where "OtherId" = 24)

if variable notnull then
    insert into public.tableName ("OtherName", "OtherPhoneNumber", "OtherAddress", "Id")
    overriding system values
    values ('foo', '205-123-4567', '123 Sample Ln', variable)
end if

Postgres 给我一个错误,内容如下:

SQL 错误 [42601]:错误:“if”处或附近的语法错误

我做错了什么?

****edit: Id 不是主键,因为有一个不同的主键名为 TableNameId****

【问题讨论】:

  • 我没有获得第一个 CTE。如果你期待Id = 24,那么你不知道Id的值会从select返回吗?
  • @TimBiegeleisen 我猜应该是IF EXISTS(…)
  • 与您的问题无关,但是:您确实应该避免使用那些可怕的引用标识符。 wiki.postgresql.org/wiki/…
  • "Id" 是主键还是唯一键?如果是,您可以简单地使用insert ... on conflict do nothing 代替
  • 如果 Id 不是唯一的,那么整个 IF 没有意义,因为“变量”只能包含 单个 值,而不是多个值。无论如何应该将variable 设置为哪个值? Name?如果是,那么您想将“名称”存储到整数列中似乎很奇怪。

标签: postgresql


【解决方案1】:

如果你想检查一个给定的id是否存在于一个表中,如果匹配则插入到另一个表,你可以使用insert ... select语法如下:

insert into public.tableName2 ("OtherName", "OtherPhoneNumber", "OtherAddress", "Id")
select 'foo', '205-123-4567', '123 Sample Ln', "Id"
from public.tableName1
where "Id" = 24

【讨论】:

  • 我希望这发生在一张桌子上。我想检查某个值是否存在,然后添加另一个值。如果没有,那就什么都不做。
  • @ColbyWilloughby 它同样适用于同一张表,而不是两个单独的表。但是,看起来您的 Id 列不是唯一的,这会很奇怪。
猜你喜欢
  • 2018-04-15
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 2018-11-07
  • 2021-03-04
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多