When writing SQL scripts, variables often need to be used to store and operate data. In Microsoft SQL Server, declaration and use variables are very simple. However, the method of defining variables in PostgreSQL is different.
Declapping and using variables in Postgresql
PostgreSQL provides a variety of mechanisms to declare and use variables in the script. The following are two common methods:
Anonymous code block:
PostgreSQL 9.0 introduced anonymous code block that allows you to use grammar to declare and operate variables in a SQL statement. For example:
DO $$
<code class="language-sql">DO $$ DECLARE v_List TEXT; BEGIN v_List := 'foobar'; SELECT * FROM dbo.PubLists WHERE Name = v_List; END $$;</code>
Parameterization query:
<code class="language-sql">CREATE TEMP TABLE temp_list (list TEXT); INSERT INTO temp_list VALUES ('foobar'); SELECT * FROM temp_list;</code>
When performing the query, you can provide the actual value as a parameter:
<code class="language-sql">SELECT * FROM dbo.PubLists WHERE Name = ;</code>
<code class="language-sql">SELECT * FROM dbo.PubLists WHERE Name = 'foobar';</code>
Variables: The variables declared in the anonymous code block are limited to the specific code block. On the other hand, the temporary table can be accessed in the entire script.
The above is the detailed content of How Do I Effectively Use Variables in PostgreSQL Scripts?. For more information, please follow other related articles on the PHP Chinese website!