return id field when executing SQL in LINQ - linq

I'm trying to execute an SQL insert query using LINQ and returning the ID field. My code does not work, can anybody tell me if my syntax is wrong?
string query = "insert into EnvironmentalReportDepts ";
query += "(fkDeptID, OrderNumber, fkEnvironmentalReportID) ";
query += "values(" + tmpDeptReport.fkDeptID + ", " + tmpDeptReport.OrderNumber + ", " + tmpDeptReport.EnvironmentalReport.EnvironmentalReportID + ") ";
query += "select scope_identity()";
var newDeptID = _database.ExecuteQuery<int>(query).ToList()[0];

Try changing
query += "select scope_identity()";
to
query += "; select scope_identity()";
Also, you may have to use
_database.ExecuteQuery<decimal>(query).ToList()[0];

change query to:
string query = "DECLARE #scope_identity int";
query += "insert into EnvironmentalReportDepts ";
query += "(fkDeptID, OrderNumber, fkEnvironmentalReportID) ";
query += "values(" + tmpDeptReport.fkDeptID + ", " + tmpDeptReport.OrderNumber + ", " + tmpDeptReport.EnvironmentalReport.EnvironmentalReportID + ") ";
query += "SET #scope_identity=##IDENTITY";
query += "select #scope_identity";

Related

JPA SPEL optional List parameter

I have a JPA query with multiple joins and optional parameters , the query works fine if there is no multiple values sent in the status list parameter but if I send multiple values its giving exception as
"Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: An expression of non-boolean type specified in a context where a condition is expected, near ','.
Below is the query, could you please help
#Query(value = select distinct a.invn, a.accid, ac.accountCode, b.Fbusinesscode" +
", b.scode, i.invtype, d.dtid, d.did " +
" from INV.BINv a " +
"join READONLY.Fbusiness b on a.FbusinessId =b.FbusinessId " +
"join READONLY.Acc ac on a.accid=ac.accid " +
"join INV.Doc c on a.invid = c.invid " +
"join INV.Dstreq d on c.docid = d.docid " +
"join INV.dassoc e " +
"on d.dassocId = e.dassocId " +
"join BLNG.InvMType AS i on e.invtypeId = i.invtypeId "+
"where (?#{#requestdto.invoiceNumber } is null OR a.InvoiceEntityNumber = ?#{#requestdto.invoiceNumber}) and " +
" (?#{#requestdto.mod} is null OR i.InvTypeName = ?#{#requestdto.mod}) and " +
" (?#{#requestdto.getStatus} is null OR e.distrstttypecode in ?#{#requestdto.getStatus}) "
Something like this should do it:
#Query("select distinct a.invn, a.accid, ac.accountCode, b.Fbusinesscode" +
", b.scode, i.invtype, d.dtid, d.did " +
" from INV.BINv a " +
"join READONLY.Fbusiness b on a.FbusinessId =b.FbusinessId " +
"join READONLY.Acc ac on a.accid=ac.accid " +
"join INV.Doc c on a.invid = c.invid " +
"join INV.Dstreq d on c.docid = d.docid " +
"join INV.dassoc e " +
"on d.dassocId = e.dassocId " +
"join BLNG.InvMType AS i on e.invtypeId = i.invtypeId "+
"where (?#{#requestdto.invoiceNumber } is null OR a.InvoiceEntityNumber = ?#{#requestdto.invoiceNumber}) and " +
" (?#{#requestdto.mod} is null OR i.InvTypeName = ?#{#requestdto.mod}) and " +
" (?#{#requestdto.status?.size() ?: 0} = 0 OR e.distrstttypecode in ?#{#requestdto.status}) "
Note that in original query you specified requestdto.getStatus which should likely be just requestdto.status.
References:
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions-operator-elvis
https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions-operator-safe-navigation

SQL query error when creating a table in PostgreSQL /SpringBoot

I am using Spring Boot and PostgreSQL to create a table in which I want to insert the latest data from another table.
I was using H2 and everything was fine but when I migrated to PostgreSQL, the error "SELECT ... FROM must be followed by a reference to the table appeared e.g. SELECT * FROM table as FOO" .
However, when modifying my query with AS, I am still having the same error.
"CREATE TABLE IF NOT EXISTS EOD AS " +
"(SELECT ID, " +
"CUSIP, " +
"NAME, " +
"ISIN, " +
"NAV, " +
"RIC, " +
"RTV," +
"VOLATILITY as volatility, " +
"CURRENCY as currency, "+
"ASK_ISSUER as ask_issuer, " +
"ASK_KECH as ask_kech, " +
"AVERAGE_SCORE as average_score, " +
"BID_ISSUER as bid_issuer, " +
"BID_KECH as bid_kech, " +
"BID_ONLY as bid_only, " +
"CREATOR as creator, " +
"DECENTER as decenter, " +
"DENOMINATION as denomination, " +
"FORCE_PUBLISH as force_publish, " +
"ISSUER_SPREAD as issuer_spread, " +
"KECH_MARGIN as kech_margin, " +
"KECH_SPREAD as kech_spread, " +
"DISTANCE_TO_BANDS_SCORE as distance_to_bands_score, " +
"DIFFERENCE_TO_LEXIFI_PRICE_SCORE as difference_to_lexifi_price_score, " +
"METRIC_C as metric_c, " +
"PRICE_EXPRESSION as price_expression, " +
"PRODUCT_TYPE as product_type, " +
"PUBLISHED as published, " +
"PUBLISHING as publishing, " +
"TIMESTAMP as timestamp " +
"FROM " +
"(" +
"SELECT * FROM RTDATABASE AS T " +
"JOIN (SELECT MAX(CONVERT(TIMESTAMP, DATETIME)) AS LATESTDATE FROM T GROUP BY ISIN)" +
") tm " +
"WHERE CONVERT(tm.TIMESTAMP, DATETIME) = tm.LATESTDATE) AS LATESTDATA;";
Any idea how to solve this issue?
Many thanks in advance !

Using Prepared Statement in Complex query

I am trying to use Prepared Statement for processing queries. The problem is I have severals if else statements that changes query based on the user input.
Here is my code
if( !star_firstName.isEmpty() || !star_lastName.isEmpty() ){
baseQuery = "select m.id, title, year, director, banner_url, trailer_url from movies m, stars s, stars_in_movies sim WHERE m.id=sim.movie_id AND s.id=sim.star_id";
}
if(!searchtext.isEmpty())
baseQuery = baseQuery + " AND upper(title) like '%" + searchtext.toUpperCase() + "%'" ;
if(!movie_year.isEmpty())
baseQuery = baseQuery + " AND year=" + movie_year;
if(!movie_director.isEmpty())
baseQuery = baseQuery + " AND upper(director) like '%" + movie_director.toUpperCase() + "%'";
if( !star_firstName.isEmpty())
baseQuery = baseQuery + " AND upper(first_name) like '%" + star_firstName.toUpperCase() + "%'" ;
if( !star_lastName.isEmpty())
baseQuery = baseQuery + " AND upper(last_name) like '%" + star_lastName.toUpperCase() + "%'" ;
if(!title1.isEmpty() ){
baseQuery = "SELECT m.id, title, year, director, banner_url, trailer_url FROM movies m where m.title like '" + title1 + "%" + "'";
}
if( !genre.isEmpty()){
baseQuery = "SELECT m.id, title, year, director, banner_url, trailer_url FROM movies m, genres g, genres_in_movies gim where g.id=gim.genre_id and m.id = gim.movie_id and g.name='" + genre + "'";
}
System.out.println(baseQuery);
ResultSet resultSet = statement.executeQuery(baseQuery);
A PreparedStatement won't help you in this case.
A PreparedStatement only helps performance if the query stays the same, and all that varies are the constants.
The other use of a PreparedStatement is to avoid the danger of SQL injection.
If that's what you are after, you could proceed like this (untested):
java.util.Vector<String> params = new Vector();
StringBuffer baseQuery = new StringBuffer("SELECT ...");
...
if (!dweebnoid.isEmpty()) {
baseQuery.append(" AND upper(dweebnoid) LIKE ?");
params.add("%" + dweebnoid + "%");
}
...
java.sql.PreparedStatement pstmt =
conn.prepareStatement(baseQuery.toString());
for (i=0; i<params.size();++i)
pstmt.setString(i+1, params.get(i));
java.sql.ResultSet resultSet = pstmt.executeQuery();

creating trigger in java jsp

I can run the following statement in SQL-developer
String fileInsertTrigger="CREATE OR REPLACE TRIGGER user_testtrigger12 "
+ "BEFORE INSERT ON user_test1 "
+ "FOR EACH ROW "
+ "DECLARE "
+ " CNT number ; "
+ " PKV user_test1.PARTY_ID%TYPE ; "
+ "BEGIN "
+ "SELECT COUNT(*) INTO CNT FROM user_test1 where PARTY_ID like ? and PARTY_ID not like ? ; "
+ "IF CNT=0 THEN "
+ "PKV:= ? ; "
+ " ELSE "
+ "SELECT ? || TRIM(LPAD(MAX(TO_NUMBER(SUBSTR(PARTY_ID,?,LENGTH(PARTY_ID)))+1),15)) into PKV "
+ "FROM user_test1 where PARTY_ID like ? and PARTY_ID not like ? ; "
+ "END IF ; "
+ ":NEW.PARTY_ID:=PKV ; "
+ "END " ;
and it works perfectly in database after putting all the required values in above query.
when I try to call it from a prepared statement in a jsp I get the following error
SQL Exception;java.sql.SQLException: Missing IN or OUT parameter at index:: 8
According to my analysis it is due to 'NEW' keyword.
Connection con=ConnectionDB.getConnection();
ArrayList dataHolder=FileUploadProcess.readExcelFile(u.getFileName());
ps=con.prepareStatement(SqlData.getFileinserttrigger());
System.out.println(u.getExtractString());
System.out.println(u.getExtractNumber());
ps.setString(1, u.getExtractString()+"%");
ps.setString(2, u.getExtractString()+"-%-%");
ps.setString(3, u.getExtractString()+"2");
ps.setString(4, u.getExtractString());
ps.setInt(5, u.getExtractNumber()+1);
ps.setString(6, u.getExtractString()+"%");
ps.setString(7, u.getExtractString()+"-%-%");
ps.executeQuery();
Has anybody got any ideas?
Thanks

hybris Flexiblesearch - where clause with enums

I successfully create and execute a flexiblesearch query with a WHERE clause comparing a custom property, added to CartModel, with a enum value.
But I don't know how to "translate" it to try on HAC (just to try and fix it before coding inside a class).
In my class I've the working code:
String MY_QUERY = "SELECT {" + CartModel.PK + "} FROM {" + CartModel._TYPECODE + "} "
+ "WHERE " + "( {" + CartModel.RESERVATIONORDERSTATUS + "} = ?reservedOnHybris)";
And I set the reservedOnHybris parameter with
searchQuery.addQueryParameter("reservedOnHybris", ReservationOrderStatus.INITIAL_STATUS);
How can I translate this to try it on the FlexibleSearch panel in the HAC?
Thanks in advance.
Ale
This should work:
String MY_QUERY = "SELECT {" + CartModel.PK + "} FROM {" + CartModel._TYPECODE + "} "
+ "WHERE " + "( {" + CartModel.RESERVATIONORDERSTATUS + "} =
({{SELECT {crse.PK} FROM {" + CartReservationStatusEnum._TYPECODE
+ " as crse} WHERE {crse.code} = '" + ?reservedOnHybris + "'}}))"
You should get the PK of your enum, you could do this by using a select query.
Try :
SELECT {PK} FROM {Cart} WHERE {RESERVATIONORDERSTATUS} = "Your status"
Basically things like "CartModel.PK" could be replaced by the String.

Resources