EF Core to make SQL Database MERGE call and get output of new inserted record along with identify column - entity-framework

We are using EF Core to make database call and we have a MERGE call to conditionally insert a record and what we want is once the record is inserted we want to get that new RECORD in the OUTPUT (along with the identify column). I am doing this avoid additional Select query post the insert. Following is our code, any guidance on how we can get the OUTPUT of the new record along with the identify column (auto generated value):
string query = $"MERGE INTO [ReceiptMaster] AS old " +
$"USING (VALUES ({receipt.ProfileID},'{receipt.TranscribeID}','{receipt.ReceiptStatusID}'," +
$"'{receipt.ReceiptTypeID}','{receipt.TransactionDate}','{receipt.ProcessTypeID}'," +
$"'{receipt.TripTranscriptionVendorID}','{receipt.AcquireTypeID}',{receipt.CategoryTypeID}," +
$"'{receipt.IsResubmitted}','{receipt.IsResubmittedByPanel}', {receipt.ScrapeJobID}, " +
$"'{receipt.TripTranscriptionPayloadID}')) " +
$"AS new (ProfileID, TranscribeID, ReceiptStatusID, ReceiptTypeID, TransactionDate, ProcessTypeID, " +
$"TripTranscriptionVendorID, AcquireTypeID, CategoryTypeID, IsResubmitted, IsResubmittedByPanel, " +
$"ScrapeJobID, TripTranscriptionPayloadID) " +
$"ON new.TranscribeID = old.TranscribeID " +
$"WHEN NOT MATCHED BY TARGET THEN INSERT (ProfileID, TranscribeID, ReceiptStatusID, ReceiptTypeID, " +
$"TransactionDate, ProcessTypeID, TripTranscriptionVendorID, AcquireTypeID, CategoryTypeID, IsResubmitted, " +
$"IsResubmittedByPanel, ScrapeJobID, TripTranscriptionPayloadID) VALUES (ProfileID, TranscribeID, ReceiptStatusID, " +
$"ReceiptTypeID, TransactionDate, ProcessTypeID, TripTranscriptionVendorID, AcquireTypeID, CategoryTypeID, " +
$"IsResubmitted, IsResubmittedByPanel, ScrapeJobID, TripTranscriptionPayloadID);";
var context = _dbContext.Database.ExecuteSqlRaw(query);
if (context == 0) return false;
else return true;
}

Related

Postgres records not being create but PK is being incremented

I am running a Python script and using pyscopg2 and wxPython extensions to add records to a local PostgreSQL database. The script runs without error. When I check the table using pgAdmin4 the records aren't there. When I add a record manually in pgAdmin4 the primary key (a serial type) has skipped ahead exactly the number of records that should have been added from the Python script. A separate, but similar, occurrence is the DELETE command is running without error but no records are deleted. When I run the same command locally all requested records are deleted. What am I not doing correctly?
I know the connection is open, I got several error messages regarding syntax and have worked those those out. I have tried running the commands by hardcoding the values rather than the variables.
sSQLMessage = ("DELETE FROM plots WHERE mapid = " + mapnum + " AND plotnum = " + plotnum)
wx.MessageBox(sSQLMessage)
cur.execute(sSQLMessage)
sSQLMessage = ("INSERT INTO plots (plotnum, mapid, plotshape, labelpnt, supplypnt, unitspnt) VALUES (" \
+ plotnum + ", " + mapnum + ", ('( " + polyCoords + " )') , '" + plotCoords + "' , '" + supplyCoords + "' , '" + unitsCoords + "');")
wx.MessageBox(sSQLMessage)
cur.execute(sSQLMessage)

Access list of object array with alias in jpa

i have written a native query in jpa which fetch list of object array
list = entityManager.createNativeQuery("select emp.card Card,emp.code Code,emp.emp_name EmpName,ln.BAL Balance, ln.cum_intr CumIntr, ln.install Install,ln.install_no InstallNo, "
+ " led.BAL ledgBAL,led.cum_intr ledgCum,led.install ledgInstall,led.install_no ledgInstallNo "
+ " from LOANS ln "
+ " inner join "
+ " LOAN_LEDGER led "
+ " on (led.EMPLOYEES_ID = ln.EMPLOYEES_ID and ln.LOAN_UID= led.LOAN_UID and (ln.bal!= led.BAL or ln.cum_intr!= led.cum_intr or ln.INSTALL != led.INSTALL )) "
+ " inner join EMPLOYEES emp "
+ " on ln.employees_id = emp.id "
+ " where led.ledger_month in "
+ " ( 201312 )").getResultList();
I assigned alias for each field.this is my code to access this object array.
Iterator it = list.iterator();
while (it.hasNext()) {
Object[] result = (Object[]) it.next();
System.err.println("Result Arrayyyyy "+result[0]);
}
Now i want to access this result array using alias . How can I do it?

Updating values in real time Talend

I'm trying to update my data with talend.I'm using tOracleOutput with the option 'update or insert' but my problem is that when there is an update i want to sum the older and the newer value of a row because my app is executing in real time.There is any help? (sorry for my bad english)
You can use a tOracleRow component containing a SQL update statement . Take the new value (from context, row, or globalMap) and use that in the update statement within tOracleRow, adding it to the existing value of the desired record.
Ex
"
UPDATE target_table
SET target_field = target_field " + globalMap.get("newVal") + "
WHERE target_id = " + globalMap.get("id") + "
"

ERROR: duplicate key value violates unique constraint "xak1fact_dim_relationship"

I am getting the below error while deleting some rows and updating the table based on a condition from java. My database is PostgreSQL 8.4. Below is the error:
ERROR: duplicate key value violates unique
constraint "xak1fact_dim_relationship"
The code cuasing this issue is below:
/**
* Commits job. This does the following:
* <OL>
* <LI> cancel previous datamart states </LI>
* <LI> drop diabled derived objects </LI>
* <LI> flip mirror relationships for objects with next states </LI>
* <LI> advance rolloff_state from start1 to complete1, from start2 to complete </LI>
* <LI> set 1/0 internal states to 0/-1 </LI>
* <LI> remove header objects with no letter rows </LI>
* <LI> mark mirror rel as OS if children are missing (e.g., semantic w/o agg build) </LI>
* <LI> mark mirror rel as OS if int-map not in sync with dim base (e.g., int-map SQL w/o semantic) </LI>
* </OL>
*/
protected void CommitJobUnprotected()
throws SQLException
{
if (_repl.epiCenterCon== null)
throw makeReplacementError(0);
boolean oldAutoCommitStatus = _repl.epiCenterCon.getAutoCommit();
try
{
_repl.epiCenterCon.setAutoCommit(false);
Statement stmt = null;
boolean committed = false;
synchronized (SqlRepl.metaChangeLock)
{
try
{
stmt = _repl.epiCenterCon.createStatement();
// update internal states for fact_dim_relationship
metaExec(stmt, "DELETE from fact_dim_relationship WHERE internal_state = -1 AND " +
" EXISTS (SELECT 1 FROM fact_dim_relationship WHERE internal_state = 1)",
" SELECT 1 from fact_dim_relationship WHERE internal_state = -1 AND " +
" EXISTS (SELECT 1 FROM fact_dim_relationship WHERE internal_state = 1)"); /*1*/
metaExec( stmt, "UPDATE fact_dim_relationship SET internal_state = internal_state - 1 " +
" WHERE EXISTS (SELECT 1 FROM fact_dim_relationship inner1 " +
" WHERE inner1.internal_state = 1 " +
" AND inner1.fact_tbl_key = fact_dim_relationship.fact_tbl_key " +
" AND inner1.dim_base_key = fact_dim_relationship.dim_base_key ) ",
" SELECT 1 FROM fact_dim_relationship " +
" WHERE EXISTS (SELECT 1 FROM fact_dim_relationship inner1 " +
" WHERE inner1.internal_state = 1 " +
" AND inner1.fact_tbl_key = fact_dim_relationship.fact_tbl_key " +
" AND inner1.dim_base_key = fact_dim_relationship.dim_base_key ) "); /*5*/
System.out.println("Update done on fact_dim_relationship");
_repl.doDrop(SqlReplLogger.DB_META, stmt, "fact_agg", "SELECT fact_agg_key FROM fact_agg f WHERE " +
" NOT EXISTS (SELECT 1 FROM fact_agg_letter l WHERE " +
" f.fact_agg_key = l.fact_agg_key) "); /*6*/
_repl.doDrop(SqlReplLogger.DB_META, stmt, "dim_base_agg", "SELECT dim_base_agg_key FROM dim_base_agg d WHERE " +
" NOT EXISTS (SELECT 1 FROM dim_base_agg_letter l WHERE " +
" d.dim_base_agg_key = l.dim_base_agg_key) "); /*6*/
CheckOutOfSync(stmt, "fact_agg", null); /*7*/
CheckOutOfSync(stmt, "dim_base_agg", null); /*7*/
metaExec( stmt, " update mirror_relationship set relation_to_current = 'Out Of Sync' " +
" where dim_col_intmap_key is not null " +
" and relation_to_current = 'One Back' " +
" and not exists ( " +
" select 1 " +
" from mirror_relationship m2, dim_col_view c, dim_col_intmap i " +
" where m2.dim_base_key = c.dim_base_key " +
" and c.dim_col_key = i.dim_col_key " +
" and i.dim_col_intmap_key = mirror_relationship.dim_col_intmap_key " +
" and m2.relation_to_current = 'One Back') ",
" SELECT 1 FROM mirror_relationship " +
" where dim_col_intmap_key is not null " +
" and relation_to_current = 'One Back' " +
" and not exists ( " +
" select 1 " +
" from mirror_relationship m2, dim_col_view c, dim_col_intmap i " +
" where m2.dim_base_key = c.dim_base_key " +
" and c.dim_col_key = i.dim_col_key " +
" and i.dim_col_intmap_key = mirror_relationship.dim_col_intmap_key " +
" and m2.relation_to_current = 'One Back') "); /*8*/
// clean out the tables used by mombuilder, aggbuilder, and semantics
metaExec( stmt, "delete from relation_intermediary", "select 1 from relation_intermediary" );
_repl.epiCenterCon.commit();
committed = true;
}
finally
{
safeMetaRollbackIfNeeded( committed );
_repl.safeClose( null, stmt );
}
} // end synchronized block
}
finally
{
_repl.epiCenterCon.setAutoCommit(oldAutoCommitStatus);
}
}
The first delete statement ran well, but while running the update it is throwing the above exception....! We support the SQLServer, Oracle and DB2, and the same code runs fine with other DBs. By the way we run these statements in a READ_COMMITTED transaction level and we are setting the autocommit off if anything fails in between we safely rolls back. If i run the above code with autocommit true the code works fine! But we should not do so. I am suspecting the Multi version concurrency control feature of PostgreSQL, am i wrongly setting the Isolation level? Please help me as early as possible. I can provide what ever the info you want.
If it is only this particular set of queries, use SET CONSTRAINT:
BEGIN;
SET CONSTRAINT = xak1fact_dim_relationship DEFERRED;
-- Do your SQL
COMMIT;
If this is a very common case, you can change your database schema to you can, change your database schema to support INITIALLY DEFERRED.

select NULL value from sql server db

i'm having a problem with a select statement.
It looks like:
myda = new SqlDataAdapter("Select * FROM tblAgenda WHERE tAgUsrId ='" + Session["usrId"] + "' AND tAgTBD = '" + Session["username"] + "' OR tAgTBD = '" + DBNull.Value + "' ", myconn);
But I have no idea how to make that DBNull.Value work. I also tried with just using "" instead, but it also doesn't work.
Any ideas on how to rewrite this statement please? Thank you.
Assuming that your session values have already been sanitised, then you can do the following:
myda = new SqlDataAdapter("Select * FROM tblAgenda WHERE tAgUsrId ='" +
Session["usrId"] + "' AND tAgTBD = '" +
Session["username"] + "' OR tAgTBD is null", myconn);
The above assumes that you want all rows where tAgTBD are null. If you want to keep the restriction the to the user ID, you'll want to add brackets around the two ORed conditions:
myda = new SqlDataAdapter("Select * FROM tblAgenda WHERE tAgUsrId ='" +
Session["usrId"] + "' AND (tAgTBD = '" +
Session["username"] + "' OR tAgTBD is null)", myconn);
If the session values haven't been sanitised, then you need to read up on SQL injection, and look at using an SqlCommand with parameters instead of constructing a string; although you may prefer to go this route anyway - it's a better habit to acquire, long term, and then you don't need to consider whether the values have been sanitised.