Home > Database > Mysql Tutorial > How Can I Use Variables in PostgreSQL Like I Do in Microsoft SQL Server?

How Can I Use Variables in PostgreSQL Like I Do in Microsoft SQL Server?

DDD
Release: 2025-01-24 20:34:12
Original
774 people have browsed it

How Can I Use Variables in PostgreSQL Like I Do in Microsoft SQL Server?

PostgreSQL Variable Usage: A Practical Guide

Microsoft SQL Server's convenient variable handling within query windows is mirrored in PostgreSQL, albeit with a slightly different approach. This guide demonstrates how to declare, assign, and utilize variables within PostgreSQL scripts.

Declaring and Using Variables in PostgreSQL

PostgreSQL employs the DO $$ anonymous code block for variable declaration and manipulation. This allows you to define variables with specific data types and assign them values. The following example illustrates this:

DO $$
DECLARE v_Name TEXT;
BEGIN
  v_Name := 'foobar';
  SELECT * FROM dbo.PubLists WHERE Name = v_Name;
  -- Further operations using v_Name
END $$;
Copy after login

Retrieving the Last Inserted ID

A common task is retrieving the ID of the last inserted row. PostgreSQL efficiently handles this using the RETURNING clause within the INSERT statement, as shown below:

DO $$
DECLARE last_inserted_id BIGINT;
BEGIN
  INSERT INTO test (name) VALUES ('Test Name')
  RETURNING id INTO last_inserted_id;

  SELECT * FROM test WHERE id = last_inserted_id;
END $$;
Copy after login

This concise method demonstrates the power and flexibility of variable usage within PostgreSQL, offering functionality comparable to Microsoft SQL Server's variable handling.

The above is the detailed content of How Can I Use Variables in PostgreSQL Like I Do in Microsoft SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template