[英]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: 您尝试执行的操作几乎没有错误:
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.