views:

1336

answers:

2

Hi,

I am trying to implement a "if exists, update, otherwise, insert" data access method in NHibernate. My database is Oracle 10g.

I am getting this "could not execute native bulk manipulation query" error when try to run this code, if I run the insert or update individualy, it works just fine.

Thanks!

string sql = @"DECLARE
                CntOfRow Number(10,0);
              BEGIN
                    SELECT count(*)
                    INTO CntOfRow
                    FROM Table1
                    WHERE 
                        QueID=:QueID

                    IF CntOfRow=0 THEN
                        INSERT INTO Table1 ...;
                    ELSE
                        UPDATE Table1 ... ;
                    END IF;
                END;";


            INHibernateSession session = NHibernateSessionManager.Instance.Session;

            try
            {
                session.BeginTransaction();
                ISQLQuery query = session.GetISession().CreateSQLQuery(sql.Replace(System.Environment.NewLine, " "));
                query.SetParameter("QueID", queID);
                query.ExecuteUpdate();
                session.CommitTransaction();
            }
            catch (Exception ex)
            {
                session.RollbackTransaction();
                throw;
            }
+2  A: 

I don't know why you get that error, but you could try this simpler PL/SQL block instead:

BEGIN
    INSERT INTO Table1 ...;
EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
        UPDATE Table1 ... ;
END;";
Tony Andrews
This SQL works better as, if another session has created but not committed the record in question, the insert will wait on the lock. Once committed, it will drop down to the exception handler. In the original, the select would not wait on the lock and would not return a row. it would then drop into the insert path, which would wait on the lock, and error when the other session commits..Look into the MERGE statement too.
Gary
it does not work either, somehow NHibernate always remove the ; from the update statement.I am getting different error this timeOracle.DataAccess.Client.OracleException ORA-06550: line 1, column 1749:\nPL/SQL: ORA-00933: SQL command not properly ended\nORA-06550: line 1, column 1123:\n
Ding
A: 

You seem to be missing an ; after the SELECT

This link might also be of interest to you.

As about inserting/updating, see MERGE statement. It works like this:

MERGE INTO t1 dest
USING (SELECT 1 pk, 11 i FROM dual) src
   ON (dest.pk = src.pk)
 WHEN NOT MATCHED THEN INSERT (dest.pk, dest.i) VALUES (src.pk, src.i)
 WHEN MATCHED THEN UPDATE SET dest.i = src.i;

Also see this topic

Marius Burz
merge into worked for my case. Thanks!FYI, The missing ; was not the cause of issue, I have ; in my complete sql, in other word, the sql I am using is valid. Somehow NHibernate does not like it.
Ding