搜索
首页数据库mysql教程postgresql 类似 oracle sql%rowcount 用法 的全局变量

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
MySQL的许可与其他数据库系统相比如何?MySQL的许可与其他数据库系统相比如何?Apr 25, 2025 am 12:26 AM

MySQL使用的是GPL许可证。1)GPL许可证允许自由使用、修改和分发MySQL,但修改后的分发需遵循GPL。2)商业许可证可避免公开修改,适合需要保密的商业应用。

您什么时候选择InnoDB而不是Myisam,反之亦然?您什么时候选择InnoDB而不是Myisam,反之亦然?Apr 25, 2025 am 12:22 AM

选择InnoDB而不是MyISAM的情况包括:1)需要事务支持,2)高并发环境,3)需要高数据一致性;反之,选择MyISAM的情况包括:1)主要是读操作,2)不需要事务支持。InnoDB适合需要高数据一致性和事务处理的应用,如电商平台,而MyISAM适合读密集型且无需事务的应用,如博客系统。

在MySQL中解释外键的目的。在MySQL中解释外键的目的。Apr 25, 2025 am 12:17 AM

在MySQL中,外键的作用是建立表与表之间的关系,确保数据的一致性和完整性。外键通过引用完整性检查和级联操作维护数据的有效性,使用时需注意性能优化和避免常见错误。

MySQL中有哪些不同类型的索引?MySQL中有哪些不同类型的索引?Apr 25, 2025 am 12:12 AM

MySQL中有四种主要的索引类型:B-Tree索引、哈希索引、全文索引和空间索引。1.B-Tree索引适用于范围查询、排序和分组,适合在employees表的name列上创建。2.哈希索引适用于等值查询,适合在MEMORY存储引擎的hash_table表的id列上创建。3.全文索引用于文本搜索,适合在articles表的content列上创建。4.空间索引用于地理空间查询,适合在locations表的geom列上创建。

您如何在MySQL中创建索引?您如何在MySQL中创建索引?Apr 25, 2025 am 12:06 AM

toCreateAnIndexinMysql,usethecReateIndexStatement.1)forasingLecolumn,使用“ createIndexIdx_lastNameEnemployees(lastName); 2)foracompositeIndex,使用“ createIndexIndexIndexIndexIndexDx_nameOmplayees(lastName,firstName,firstName);” 3)forauniqe instex,creationexexexexex,

MySQL与Sqlite有何不同?MySQL与Sqlite有何不同?Apr 24, 2025 am 12:12 AM

MySQL和SQLite的主要区别在于设计理念和使用场景:1.MySQL适用于大型应用和企业级解决方案,支持高性能和高并发;2.SQLite适合移动应用和桌面软件,轻量级且易于嵌入。

MySQL中的索引是什么?它们如何提高性能?MySQL中的索引是什么?它们如何提高性能?Apr 24, 2025 am 12:09 AM

MySQL中的索引是数据库表中一列或多列的有序结构,用于加速数据检索。1)索引通过减少扫描数据量提升查询速度。2)B-Tree索引利用平衡树结构,适合范围查询和排序。3)创建索引使用CREATEINDEX语句,如CREATEINDEXidx_customer_idONorders(customer_id)。4)复合索引可优化多列查询,如CREATEINDEXidx_customer_orderONorders(customer_id,order_date)。5)使用EXPLAIN分析查询计划,避

说明如何使用MySQL中的交易来确保数据一致性。说明如何使用MySQL中的交易来确保数据一致性。Apr 24, 2025 am 12:09 AM

在MySQL中使用事务可以确保数据一致性。1)通过STARTTRANSACTION开始事务,执行SQL操作后用COMMIT提交或ROLLBACK回滚。2)使用SAVEPOINT可以设置保存点,允许部分回滚。3)性能优化建议包括缩短事务时间、避免大规模查询和合理使用隔离级别。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中