목차
General rules
Cursors
Arrays
ROWNUM
 %ROWCOUNT
Formating code
Functions
Procedures
Views
Triggers
데이터 베이스 MySQL 튜토리얼 postgresql 类似 oracle sql%rowcount 用法 的全局变量

postgresql 类似 oracle sql%rowcount 用法 的全局变量

Jun 07, 2016 pm 03:36 PM
oracle postgresql

http://wiki.openbravo.com/wiki/ERP/2.50/Developers_Guide/Concepts/DB/PL-SQL_code_rules_to_write_Oracle_and_Postgresql_code Procedure Language rules Openbravo ERP supports Oracle and PostgreSQL database engines. This is a set of recommendat

http://wiki.openbravo.com/wiki/ERP/2.50/Developers_Guide/Concepts/DB/PL-SQL_code_rules_to_write_Oracle_and_Postgresql_code


Procedure Language rules

Openbravo ERP supports Oracle and PostgreSQL database engines.

This is a set of recommendations for writing Procedure Language that works on both database backends (when possible) or that can be automatically translated by DBSourceManager. These recommendations assume that you have written code in Oracle and that you want to port it to PostgreSQL.


General rules

This a list of general rules that assure that PL runs properly on different database backgrounds.

  • JOIN statement. Change the code replacing the (+) by LEFT JOIN or RIGHT JOIN
  • In XSQL we use a questionmark (?) as parameter placeholder. If it is a NUMERIC variable use TO_NUMBER(?). For dates use TO_DATE(?).
  • Do not use GOTO since PostgreSQL does not support it. To get the same functionality that GOTO use boolean control variables and IF/THEN statements to check if the conditions are TRUE/FALSE.
  • Replace NVL commands by COALESCE.
  • Replace DECODE commands by CASE. If the CASE is NULL the format is:
CASE WHEN variable IS NULL THEN X ELSE Y END
로그인 후 복사

If the variable is the result of concatenating several strings () are required.

  • Replace SYSDATE commands by NOW()
  • PostgreSQL treats "" and NULL differently. When checking for a null variable special care is required.
  • When a SELECT is inside a FROM clause a synonym is needed.
SELECT * FROM (SELECT 'X' FROM DUAL) A
로그인 후 복사
  • When doing SELECT always use AS.
SELECT field AS field_name FROM DUAL
로그인 후 복사
  • PostgreSQL does not support synonyms of tables in UPDATE, INSERT or DELETE operations.
  • PostgreSQL 8.1 (but fixed in 8.2 version) does not support updates like:
UPDATE TABLE_NAME SET (A,B,C) = (SELECT X, Y, Z FROM ..
로그인 후 복사

The following order is correctly accepted:

UPDATE TABLE_NAME SET A = (SELECT X FROM ..), B = (SELECT Y FROM .),C = (SELECT Z FROM ..)
로그인 후 복사
  • PostgreSQL does not support using the table name in the fields to update.
  • PostgreSQL does not support the DELETE TABLE command. DELETE FROM Table should be used instead.
  • PostgreSQL does not support parameters like '1' in the ORDER BY or GROUP BY clause. A numeric without commas can be used.
  • PostgreSQL does not support the CURRENT OF clause. An active checking of register to update should be used.
  • PostgreSQL does not support COMMIT. It does automatically an explicit COMMIT between BEGIN END blocks. Throwing an exception produces a ROLLBACK.
  • PostgreSQL does not support SAVEPOINT. BEGIN, END and ROLLBACK should be used instead to achieve the same functionality.
  • PostgreSQL does not support CONNECT.
  • Both Oracle and PostgreSQL do not support using variable names that match column table names. For example, use v_IsProcessing instead of IsProcessing.
  • PostgreSQL does not support EXECUTE IMMEDIATE ... USING. The same functionality can be achieved using SELECT and replacing the variables with parameters manually.
  • PostgreSQL requires () in calls to functions without parameters.
  • DBMS.OUTPUT should be done in a single line to enable the automatic translator building the comment.
  • In PostgreSQL any string concatenated to a NULL string generates a NULL string as result. It's is recommended to use a COALESCE or initialize the variable to ''.
    • Notice that in Oracle null||'a' will return 'a' but in PostgrSQL null, so the solution would be coalesce(null,'')||'a' that will return the same for both. But if the we are working with Oracle's NVarchar type this will cause an ORA-12704: character set mismatch error, to fix it it is possible to use coalesce(to_char(myNVarCharVariable),)||'a'.
  • Instead of doing
COALESCE(variable_integer, <em>)</em>
로그인 후 복사

do

COALESCE(variable_integer, 0)
로그인 후 복사

to guarantee that it will also work in PostgreSQL.

  • PostgreSQL does the SELECT FOR UPDATE at a table level while Oracle does it at a column level.
  • PostgreSQL does not support INSTR command with three parameters. SUBSTR should be used instead.
  • In Oracle SUBSTR(text, 0, Y) and SUBSTR(text, 1, Y) return the same result but not in PostgreSQL. SUBSTR(text, 1, Y) should be used to guarantee that it works in both databases.
  • PostgreSQL does not support labels like > (but it can be commented out).
  • In dates comparisons is often needed a default date when the reference is null, January 1, 1900 or December 31, 9999 should be used.
  • When is specified a date as a literal it is necessary to use always the to_date function with the correspondent format mask.
RIGHT: COALESCE(movementdate, TO_DATE('01-01-1900', 'DD-MM-YYYY'))
로그인 후 복사


Cursors

There are two different ways of using cursors: in FETCH clauses and in FOR loops. For FETCH cursor type no changes are required (except for %ISOPEN and %NOTFOUND methods that are explained below).

Oracle FETCH cursor declarations:

CURSOR	Cur_SR IS
로그인 후 복사

should be translated in PostgreSQL into:

DECLARE Cur_SR CURSOR FOR
로그인 후 복사

For cursors in FOR loops the format suggested is:

TYPE RECORD IS REF CURSOR;
	Cur_Name RECORD;
로그인 후 복사

that is both accepted by Oracle and PostgreSQL.


Arrays

In Oracle, arrays are defined in the following way:

TYPE ArrayPesos IS VARRAY(10) OF INTEGER;
  v_pesos ArrayPesos;
v_dc2 := v_dc2 + v_pesos(v_contador)*v_digito;
로그인 후 복사

but in PostgresSQL they are defined as:

v_pesos integer[];
v_dc2 := v_dc2 + v_pesos[v_contador]*v_digito;
로그인 후 복사


ROWNUM

To limit the number of registers that a SELECT command returns, a cursor needs to be created and read the registers from there. The code could be similar to:

--Initialize counter
v_counter := initial_value;
--Create the cursor
FOR CUR_ROWNUM IN (SELECT CLAUSE)
LOOP
  -- Some sentences
  --Increment the counter
  v_counter := v_counter + 1;
  --Validate condition
  IF (v_counter = condition_value) THEN
    EXIT;
  END IF;
END LOOP;
로그인 후 복사


 %ROWCOUNT

SQL%ROWCOUNT cannot be used directly in PostgreSQL. To convert the SQL%ROWCOUNT into PostgreSQL its value should be defined in a variable. For example:

GET DIAGNOSTICS rowcount := ROW_COUNT;
로그인 후 복사

In place of SQL%ROWCOUNT the previously declared variable should be used.


 %ISOPEN, %NOTFOUND

PostgreSQL cursors do not support %ISOPEN or %NOTFOUND. To address this problem %ISOPEN can be replaced by a boolean variable declared internally in the procedure and is updated manually when the cursor is opened or closed.


Formating code
  • To export properly a RAISE NOTICE from postgresql to xml files you have to follow this syntax:
RAISE NOTICE '%', '@Message@' ;
로그인 후 복사
  • To export properly a RAISE EXCEPTION from postgresql to xml files you have to add the following comment at the end of the command; --OBTG:-20000--
RAISE EXCEPTION '%', '@Message@' ; --OBTG:-20000--
로그인 후 복사
  • In a IF clause is very important to indent the lines within the IF.
 IF (CONDITION)
    COMMAND;
 END IF;
로그인 후 복사
  • The functions with output parameters have to be invoked with select * into.
 SELECT * into VAR from FUNCTION();
로그인 후 복사
  • The end of the functions have to be defined as following to be exported properly:
 END ; $BODY$
 LANGUAGE 'plpgsql' VOLATILE
 COST 100;
로그인 후 복사
  • The cast used by postgresql is not supported by Dbsourcemanager. Instead of using :: type, use a function to convert the value
  :: interval -> to_interval(,)
  :: double precision -> to_number()
로그인 후 복사
Elements not supported by dbsource manager
  • Functions that return "set of tablename"
  • Functions that return and array
  • Functions using regular expresions
  • Column with type not included on the table on the following document: http://wiki.openbravo.com/wiki/ERP/2.50/Developers_Guide/Concepts/DB/Tables#Supported_Column_Data_types

Functions

PERFORM and SELECT are the two commands that allow calling a function. Since PostgreSQL does not accept default function parameters we define an overloaded function with default parameters.

To allow the automatic translator to do its job the following recommendations should be followed:

  • The AS and the IS should not contain spaces to the left
  • The function name should not be quoted
  • In functions, the END should go at the beginning of the line without any spaces to the left and with the function name.


Procedures

There are two ways of invoking procedures from PosgreSQL:

  • Using the format variable_name := Procedure_Name(...);
  • Using a SELECT. This is the method used for procedures that return more than one parameter.


Views

PostgreSQL does not support update for the views. If there is the need of updating a view a set of rules should be created for the views that need to be updated.

In PostgreSQL there are no table/views USER_TABLES or USER_TAB_COLUMNS. They should be created from PostgreSQL specific tables like pg_class or pg_attribute.


Triggers

Rules that the triggers should follow:

  • As general rule, is not desirable to modify child columns in a trigger of the parent table, because it is very usual that child trigger have to consult data from parent table, origin a mutating table error.
  • The name should not be quoted (") because PostgreSQL interprets it literally.
  • All the triggers have a DECLARE before the legal notice. In PostgreSQL it is necessary to do a function declaration first and then the trigger's declaration that executes the function.
  • PostgreSQL does not support the OF ..(columns).. ON Table definition. It is necessary to include the checking inside the trigger.
  • PostgreSQL does not support lazy evaluation. For example the following sentence works in Oracle but not in PostgreSQL:
IF INSERTING OR (UPDATING AND :OLD.FIELD = <em>) THEN</em>
로그인 후 복사

The correct way of expressing this is:

IF INSERTING THEN 
 ... IF UPDATING THEN 
 IF :OLD.NAME = <em> THEN</em>
로그인 후 복사
  • Triggers in PostgreSQL always return something. Depending on the type of operation it returns OLD (DELETE) or NEW (INSERT/UPDATE). It should be placed at the end of the trigger and before the exceptions if there are any.

If you are using the automatic translator consider that:

  • The last EXCEPTION in the trigger should not have spaces to its left. The translator considers this the last exception and uses it to setup the right return value.
  • The last END should not have spaces to its left. The indentation is used to determine where function ends.
  • Beware that if you add an statement like "IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;" just before the EXCEPTION statement, it might be removed by the automatic translator.

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

오라클을 열 수 없다면해야 할 일 오라클을 열 수 없다면해야 할 일 Apr 11, 2025 pm 10:06 PM

Oracle에 대한 솔루션은 개설 할 수 없습니다. 1. 데이터베이스 서비스 시작; 2. 청취자를 시작하십시오. 3. 포트 충돌을 확인하십시오. 4. 환경 변수를 올바르게 설정하십시오. 5. 방화벽이나 바이러스 백신 소프트웨어가 연결을 차단하지 않도록하십시오. 6. 서버가 닫혀 있는지 확인하십시오. 7. RMAN을 사용하여 손상된 파일을 복구하십시오. 8. TNS 서비스 이름이 올바른지 확인하십시오. 9. 네트워크 연결 확인; 10. Oracle 소프트웨어를 다시 설치하십시오.

Oracle Cursor를 닫는 문제를 해결하는 방법 Oracle Cursor를 닫는 문제를 해결하는 방법 Apr 11, 2025 pm 10:18 PM

Oracle Cursor Closure 문제를 해결하는 방법에는 다음이 포함됩니다. Close 문을 사용하여 커서를 명시 적으로 닫습니다. For Update 절에서 커서를 선언하여 범위가 종료 된 후 자동으로 닫히십시오. 연관된 PL/SQL 변수가 닫히면 자동으로 닫히도록 사용 절에서 커서를 선언하십시오. 예외 처리를 사용하여 예외 상황에서 커서가 닫혀 있는지 확인하십시오. 연결 풀을 사용하여 커서를 자동으로 닫습니다. 자동 제출을 비활성화하고 커서 닫기를 지연시킵니다.

Oracle 데이터베이스를 이끄는 방법 Oracle 데이터베이스를 이끄는 방법 Apr 11, 2025 pm 08:42 PM

Oracle 데이터베이스 페이징은 rownum pseudo-columns 또는 fetch 문을 사용하여 구현합니다. Fetch 문은 지정된 첫 번째 행 수를 얻는 데 사용되며 간단한 쿼리에 적합합니다.

Oracle Loop에서 커서를 만드는 방법 Oracle Loop에서 커서를 만드는 방법 Apr 12, 2025 am 06:18 AM

Oracle에서 FOR 루프 루프는 커서를 동적으로 생성 할 수 있습니다. 단계는 다음과 같습니다. 1. 커서 유형을 정의합니다. 2. 루프를 만듭니다. 3. 커서를 동적으로 만듭니다. 4. 커서를 실행하십시오. 5. 커서를 닫습니다. 예 : 커서는 상위 10 명의 직원의 이름과 급여를 표시하기 위해주기별로 만들 수 있습니다.

Oracle 데이터베이스를 중지하는 방법 Oracle 데이터베이스를 중지하는 방법 Apr 12, 2025 am 06:12 AM

Oracle 데이터베이스를 중지하려면 다음 단계를 수행하십시오. 1. 데이터베이스에 연결하십시오. 2. 즉시 종료; 3. 셧다운은 완전히 중단됩니다.

HDFS에서 CentOS를 구성하는 데 어떤 단계가 필요합니까? HDFS에서 CentOS를 구성하는 데 어떤 단계가 필요합니까? Apr 14, 2025 pm 06:42 PM

Centos 시스템에서 Hadoop 분산 파일 시스템 (HDF)을 구축하려면 여러 단계가 필요합니다. 이 기사는 간단한 구성 안내서를 제공합니다. 1. 초기 단계에서 JDK를 설치할 준비 : 모든 노드에 JavadevelopmentKit (JDK)을 설치하면 버전이 Hadoop과 호환되어야합니다. 설치 패키지는 Oracle 공식 웹 사이트에서 다운로드 할 수 있습니다. 환경 변수 구성 : /etc /프로파일 파일 편집, Java 및 Hadoop 설정 설정 시스템에서 JDK 및 Hadoop의 설치 경로를 찾을 수 있습니다. 2. 보안 구성 : SSH 비밀번호가없는 로그인 SSH 키 : 각 노드에서 ssh-keygen 명령을 사용하십시오.

Oracle Dynamic SQL을 만드는 방법 Oracle Dynamic SQL을 만드는 방법 Apr 12, 2025 am 06:06 AM

SQL 문은 Oracle의 동적 SQL을 사용하여 런타임 입력을 기반으로 작성 및 실행할 수 있습니다. 단계에는 다음이 포함됩니다 : 동적으로 생성 된 SQL 문을 저장할 빈 문자열 변수 준비. 즉시 실행 또는 준비 명령문을 사용하여 동적 SQL 문을 컴파일하고 실행하십시오. 바인드 변수를 사용하여 사용자 입력 또는 기타 동적 값을 동적 SQL로 전달하십시오. 동적 SQL 문을 실행하려면 즉시 실행 또는 실행을 사용하십시오.

Oracle에서 데이터베이스를 열는 방법 Oracle에서 데이터베이스를 열는 방법 Apr 11, 2025 pm 10:51 PM

Oracle 데이터베이스를 열기위한 단계는 다음과 같습니다. Oracle 데이터베이스 클라이언트를 열고 데이터베이스 서버에 연결하십시오. username/password@servername sqlplus 명령을 사용하여 데이터베이스를 엽니 다.

See all articles