简体   繁体   English

如何在SELECT语句中使用postgres变量?

[英]How can I use a postgres variable in my SELECT statement?

I'm storing a value in a variable featureId and then trying to use that value in my SELECT statement, but postgres seems to be taking the name literally and looking for a column called "featureid". 我将一个值存储在变量featureId ,然后尝试在SELECT语句中使用该值,但是postgres似乎是从字面上取该名称,并正在寻找一列名为“ featureid”的列。 I'm getting an error "ERROR: column "featureid" does not exist LINE 4: featureId," 我收到错误消息“错误:列“ featureid”不存在第4行:featureId,”

My code is below. 我的代码如下。 How can I use the value of the variable in my SELECT statement? 如何在SELECT语句中使用变量的值?

SELECT id INTO featureId FROM tableA WHERE NAME = 'some value';

INSERT INTO tableB (client_id, feature_id, does_have)
  SELECT
  id,
  featureId,
  TRUE
FROM tableA

Without a declared variable your SELECT INTO is the version of SELECT INTO that creates a table . 如果没有声明的变量你的SELECT INTO是版本SELECT INTO创建的表 To see it for yourself try: 要亲自查看,请尝试:

SELECT id
       INTO featureid
       FROM tablea
       WHERE name = 'some value';

SELECT *
       FROM featureid;

For assigning the value to a variable the variable must be declared. 为了将值分配给变量,必须声明变量。 You can use an anonymous DO block. 您可以使用匿名DO块。

DO
$$
DECLARE
  featureid tablea.id%TYPE;
BEGIN
  SELECT id
         INTO featureid
         FROM tablea
         WHERE name = 'some value';

  INSERT INTO tableb
              (client_id,
               feature_id,
               does_have)
              SELECT id,
                     featureid,
                     true
                     FROM tablea;
END;
$$
LANGUAGE plpgsql;

There are few errors on what you're tryng to do: 您尝试执行的操作几乎没有错误:

  • sql is declarative language so you're asking what to do not how to do and this is for this reason that you cannot store variables and some statements like declare and begin-end should be used in trigger and not in a simple query. sql是声明性语言,因此您要问该怎么做,因此,您无法存储变量,某些声明(如clarify和begin-end)应在触发器中使用,而不应在简单查询中使用。
  • you are executing two statements: select and insert into and they are executed one after the other, so once again you cannot store a variable. 您正在执行两个语句: selectinsert into ,它们又一个接一个地执行,因此您不能再次存储变量。
  • insert into, insert a single record but potentially you're tryng to retrieve more data with your select statement (if NAME is not unique) 插入,插入一条记录,但可能会尝试用select语句检索更多数据(如果NAME不是唯一的)

if 'some-value' is a known constant and NAME is unique just insert that value in the where clause of the insert into. 如果'some-value'是一个已知常量,并且NAME是唯一的,只需将该值插入insert的where子句中即可。 If you're tryng to insert more data take a look on bulk insert syntax of postgres: bulk insert 如果您想插入更多数据,请查看postgres的批量插入语法: bulk insert

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM