Home >Database >Mysql Tutorial >How to Store PostgreSQL Query Results in PL/pgSQL Variables?

How to Store PostgreSQL Query Results in PL/pgSQL Variables?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-24 22:56:11923browse

How to Store PostgreSQL Query Results in PL/pgSQL Variables?

Efficiently Storing PostgreSQL Query Results in PL/pgSQL Variables

PL/pgSQL, PostgreSQL's procedural language, provides a streamlined method for storing query results in variables. Let's examine a practical example:

<code class="language-sql">CREATE OR REPLACE FUNCTION test(x numeric)
RETURNS character varying AS
$BODY$
DECLARE
  name character varying(255);
BEGIN
  SELECT test_table.name INTO name FROM test_table WHERE id = x;
  RETURN name;
END;
$BODY$ LANGUAGE plpgsql;</code>

This function demonstrates how to store the result of a query into a variable. The core element is the SELECT ... INTO statement:

<code class="language-sql">SELECT test_table.name INTO name FROM test_table WHERE id = x;</code>

This statement retrieves the name field from the test_table where the id column matches the input parameter x, and assigns the retrieved value to the name variable. Note the use of test_table.name; this fully qualified column name is crucial to prevent ambiguity and potential errors. The function then returns the stored value.

The above is the detailed content of How to Store PostgreSQL Query Results in PL/pgSQL Variables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn