在存储过程中动态更新

时间:2017-04-13 04:46:40

标签: database oracle stored-procedures

这是动态选择查询SP,如果值不为null,则包含在where子句中,否则不包括。

create or replace PROCEDURE GET_STORE(
       _storeId IN NUMBER DEFAULT NULL,
       _storename IN VARCHAR2 DEFAULT NULL,
       _return_Result OUT SYS_REFCURSOR
      )AS
      BEGIN
      OPEN _return_Result FOR
      SELECT S.*  FROM STORE  S 
      WHERE (NVL(_storeId,0) =0 OR S.STOREID=_storeId)
            AND (_storename IS NULL OR S.STORENAME=_storename);
 END RD_CITY;

我们如何为更新做同样的事情,意味着更新那些非空的列。

2 个答案:

答案 0 :(得分:1)

您真的想知道要更新的行(密钥),否则您将更新整个表。因此,您需要在表上使用每个行唯一的主键(我添加了一个名为storekey的列)。然后,您可以使用nvl函数仅更新非空值:

create or replace PROCEDURE UPDATE_STORE(
       pstorekey IN NUMBER,
       pstoreid IN VARCHAR2 DEFAULT NULL,
       pstorename IN VARCHAR2 DEFAULT NULL
      )
AS
BEGIN

    update store
    set storeid = nvl(pstoreid,storeid),
    storename = nvl(pstorename,storename)
    where storekey = pstorekey;

    commit;

END update_store;

答案 1 :(得分:0)

CREATE OR REPLACE PROCEDURE GET_STORE(
  _storeId       IN  STORE.STOREID%TYPE   DEFAULT NULL,
  _storename     IN  STORE.STORENAME%TYPE DEFAULT NULL,
  _return_Result OUT SYS_REFCURSOR
)
AS
BEGIN
  OPEN _return_Result FOR
    SELECT *
    FROM   STORE
    WHERE  ( _storeId   IS NULL OR STOREID=_storeId )
    AND    ( _storename IS NULL OR STORENAME=_storename );
END GET_STORE;
/

CREATE OR REPLACE PROCEDURE UPDATE_STORE(
  _storeId       IN  STORE.STOREID%TYPE   DEFAULT NULL,
  _storename     IN  STORE.STORENAME%TYPE DEFAULT NULL,
  _othervalue    IN  STORE.OTHERVALUE%TYPE
)
AS
BEGIN
  UPDATE store
    SET   othervalue = _othervalue
    WHERE  ( _storeId   IS NULL OR STOREID=_storeId )
    AND    ( _storename IS NULL OR STORENAME=_storename );
END UPDATE_STORE;
/