Subquery on java error - java

hi guys I tried to make query on java for access data from database but when I compile the error is syntax error at or near "v", when I try to compile my query on postgresql it work and the data can show, but when I compile on eclipse it can't
this the query
#Override
protected StringBuffer buildQuery(String sql, Object... objects) {
StringBuffer sbSQL = new StringBuffer("SELECT a.master_user_id, b.name, d.group_name, a.role, "
+ "(SELECT count (v.id) FROM project_member_dtl v "
+ "LEFT JOIN project_timeline p ON v.project_timeline_id = p.id "
+ "LEFT JOIN master_project_dtl j ON p.master_project_dtl_rid = j.rid "
+ "LEFT JOIN master_project aa ON j.master_project_sid = aa.sid "
+ "where ((v.member_plan_date > now()) AND (v.member_real_date IS NULL)) "
+ "AND j.is_freeze = 'n' "
+ "AND p.is_active = 'y' "
+ "AND aa.is_deleted = 'n' "
+ "AND v.master_user_id = a.master_user_id"
+ "AND v.master_role_id = a.master_role_id ) as in_progress, "
+ "(SELECT count (w.id) FROM project_member_dtl w "
+ "LEFT JOIN project_timeline q ON w.project_timeline_id = q.id "
+ "LEFT JOIN master_project_dtl k ON q.master_project_dtl_rid = k.rid "
+ "LEFT JOIN master_project bb ON k.master_project_sid = bb.sid "
+ "where ((w.member_plan_date < now()) "
+ "AND (w.member_real_date IS NULL)) "
+ "AND k.is_freeze = 'n' "
+ "AND q.is_active = 'y' "
+ "AND bb.is_deleted = 'n' "
+ "AND w.master_user_id = a.master_user_id "
+ "AND w.master_role_id = a.master_role_id ) as in_progress_late, "
+ "(SELECT count (x.id) FROM project_member_dtl x "
+ "LEFT JOIN project_timeline r ON x.project_timeline_id = r.id "
+ "LEFT JOIN master_project_dtl l ON r.master_project_dtl_rid = l.rid "
+ "LEFT JOIN master_project cc ON l.master_project_sid = cc.sid "
+ "where (x.member_plan_date IS NULL) "
+ "AND l.is_freeze = 'n' AND r.is_active = 'y' "
+ "AND cc.is_deleted = 'n' "
+ "AND x.master_user_id = a.master_user_id "
+ "AND x.master_role_id = a.master_role_id ) as waiting_list, "
+ "(SELECT count (y.id) FROM project_member_dtl y"
+ "LEFT JOIN project_timeline s ON y.project_timeline_id = s.id "
+ "LEFT JOIN master_project_dtl m ON s.master_project_dtl_rid = m.rid "
+ "LEFT JOIN master_project dd ON m.master_project_sid = dd.sid "
+ "where (y.member_plan_date > y.member_real_date) "
+ "AND m.is_freeze = 'n' AND s.is_active = 'y' "
+ "AND dd.is_deleted = 'n' "
+ "AND y.master_user_id = a.master_user_id "
+ "AND y.master_role_id = a.master_role_id ) as finish_on_time, "
+ "(SELECT count (z.id) FROM project_member_dtl z "
+ "LEFT JOIN project_timeline t ON z.project_timeline_id = t.id"
+ "LEFT JOIN master_project_dtl n ON t.master_project_dtl_rid = n.rid"
+ "LEFT JOIN master_project ee ON n.master_project_sid = ee.sid"
+ "where (z.member_plan_date < z.member_real_date)"
+ "AND n.is_freeze = 'n' AND t.is_active = 'y'"
+ "AND ee.is_deleted = 'n' "
+ "AND z.master_user_id = a.master_user_id "
+ "AND z.master_role_id = a.master_role_id ) as finish_over_time"
+ "FROM project_member_dtl a");
sbSQL.append("LEFT JOIN master_user b ON a.master_user_id = b.id ");
sbSQL.append("LEFT JOIN user_group c ON a.master_user_id = c.master_user_id ");
sbSQL.append("LEFT JOIN master_group d ON c.group_id = d.id ");
sbSQL.append(sql);
return sbSQL;
}
thanks

It's a typo. Make sure you keep a space at the end of each line
+"AND v.master_user_id = a.master_user_id "
In the first query you missed a space
+"AND v.master_user_id = a.master_user_id"
+ "AND v.master_role_id = a.master_role_id ) as in_progress, "
Now the query would be
...AND v.master_user_id = a.master_user_idAND v.master_role_id =....
SQL engine thinks that a.master_user_idAND is a column. So the next v is a problem. That's why the error
syntax error at or near "v"

Related

Pass Nullable values using Preparement state

I have this query, and I would like to pass the null value. How to do this using Preparement state
The column that must be null is E.RTCA_CD_QMNUM IN (:1)
String sqlSigiop = "SELECT E.RTCA_CD_QMNUM"
+ ", E.RTIT_NR_ITEM"
+ ", D.RTSI_NR_SUBITEM"
+ ", B.PLOP_DT_INICIO"
+ ", B.PLOP_DT_FECHAMENTO"
+ ", D.RTSI_DT_MAIS_CEDO"
+ ", A.SSRT_CD_STATUS_SUBITEM_RT"
+ ", D.RTSI_DT_MAIS_TARDE"
+ ", A.PORT_DT_INCLUSAO"
+ ", C.PLCO_DS_PLANEJ_CONFIG"
+ ", F.ROTA_NM_ROTA"
+ ", H.CLLO_NM_CLUSTER_LOG"
+ ", G.ATEM_DT_INICIO"
+ ", I.TIAM_DS_TIPO_ATEND_MAR "
+ "FROM SIGIOP.PLANEJAMENTO_OPERACIONAL_RT A "
+ "INNER JOIN SIGIOP.PLANEJAMENTO_OPERACIONAL B ON B.PLOP_SQ_PLANEJ_OPER = A.PLOP_SQ_PLANEJ_OPER "
+ "INNER JOIN SIGIOP.PLANEJAMENTO_CONFIG C ON C.PLCO_SQ_PLANEJ_CONFIG = B.PLCO_SQ_PLANEJ_CONFIG "
+ "INNER JOIN SIGIOP.RT_SUBITEM D ON D.RTSI_CD_RTSUBITEM = A.RTSI_CD_RTSUBITEM "
+ "INNER JOIN SIGIOP.RT_ITEM E ON E.RTIT_CD_RTITEM = D.RTIT_CD_RTITEM "
+ "INNER JOIN SIGIOP.ROTA F ON F.ROTA_SQ_ROTA = A.ROTA_SQ_ROTA "
+ "INNER JOIN SIGIOP.ATENDIMENTO_MAR G ON G.ATEM_SQ_ATEND_MAR = A.ATEM_SQ_ATEND_MAR "
+ "INNER JOIN SIGIOP.CLUSTER_LOG H ON H.CLLO_SQ_CLUSTER_LOG = G.CLLO_SQ_CLUSTER_LOG "
+ "INNER JOIN SIGIOP.TIPO_ATENDIMENTO_MAR I ON I.TIAM_SQ_TIPO_ATEND_MAR = G.TIAM_SQ_TIPO_ATEND_MAR "
+ "WHERE (B.PLOP_DT_FECHAMENTO >= TO_DATE('"+dataInicio+"', 'DDMMYYYY') OR B.PLOP_DT_FECHAMENTO IS NULL)"
+ "AND (B.PLOP_DT_FECHAMENTO < TO_DATE('"+dataFim+"', 'DDMMYYYY') OR B.PLOP_DT_FECHAMENTO IS NULL) "
+ "AND A.MORE_SQ_MOTIVO_REPLANEJ IS NULL "
+ "AND B.PLOP_IN_STATUS = 2 "
+ "AND E.RTCA_CD_QMNUM IN (:1) "
+ "ORDER BY E.RTCA_CD_QMNUM, E.RTIT_NR_ITEM, D.RTSI_NR_SUBITEM, B.PLOP_DT_INICIO";
/
Statement stSigiop = cnnSigiop.createStatement();
ResultSet resultSigiop = stSigiop.executeQuery(sqlSigiop.replace(nullable ":1", rts.toString().replace("[", "").replace("]", "")));
while (resultSigiop.next()) {TO DO}
you have to change your query to this :
...
+ "AND (E.RTCA_CD_QMNUM IS NULL OR E.RTCA_CD_QMNUM IN (:1)) "
...

SQLiteException: near "FROM": syntax error multiple Joins

Can anyone see if there is an error in my query here, it's my first attempt at multiple Joins, below is the logcat error. Thanks in advance
android.database.sqlite.SQLiteException: near "FROM": syntax error
(code 1 SQLITE_ERROR[1]): , while compiling: SELECT SUM(A.quantity),
A.ingredient, A.recipe, B.ingredient_type, B.measurement_name, C.id,
D.plan_name, FROM QUANTITY AS A JOIN INGREDIENTS AS B ON A.ingredient
= B.ingredient_name JOIN PLAN_RECIPES AS C ON A.recipe = C.recipe_name JOIN MEAL_PLAN AS D ON C.id = D.plan_recipe GROUP BY A.ingredient
WHERE D.plan_name LIKE ?
Code
public void loadIngredient() {
shopList.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String RECIPE_SEARCH = " SELECT SUM(A.quantity), A.ingredient, A.recipe, B.ingredient_type, B.measurement_name, C.id, D.plan_name, " +
"FROM " + DatabaseManager.TABLE_QUANTITY + " AS A JOIN " + DatabaseManager.TABLE_INGREDIENTS +
" AS B ON A.ingredient = B.ingredient_name" + " JOIN " + DatabaseManager.TABLE_PLAN_RECIPES + " AS C ON A.recipe = C.recipe_name " +
" JOIN " + DatabaseManager.TABLE_MEAL_PLAN + " AS D ON C.id = D.plan_recipe GROUP BY A.ingredient";
String selectQuery = "";
selectQuery = RECIPE_SEARCH + " WHERE D.plan_name LIKE ?";
c = db.rawQuery(selectQuery, new String[]{"%" + search + "%"});
if (c.moveToFirst()) {
do {
Shopping_List shopping_list = new Shopping_List();
shopping_list.setQuantity(c.getDouble(c.getColumnIndex("quantity")));
shopping_list.setIngredient_name(c.getString(c.getColumnIndex("ingredient_name")));
shopping_list.setIngredient_type(c.getString(c.getColumnIndex("ingredient_type")));
shopping_list.setMeasurement_name(c.getString(c.getColumnIndex("measurement_name")));
shopList.add(shopping_list);
} while (c.moveToNext());
c.close();
}
}
There are several problems in your code.
The 1st is a comma that you must remove after D.plan_name inside the variable RECIPE_SEARCH right before the FROM clause.
The 2nd is the WHERE clause that must precede the GROUP BY clause.
The 3d is that you must alias the column SUM(A.quantity) that is returned by your query so you can retrieve it by that alias, say quantity.
The 4th is that there is no column ingredient_name returned by your query, but I assume this is the column A.ingredient which should be aliased to ingredient_name.
So change to this:
public void loadIngredient() {
shopList.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String RECIPE_SEARCH =
"SELECT SUM(A.quantity) quantity, A.ingredient ingredient_name, A.recipe, B.ingredient_type, B.measurement_name, C.id, D.plan_name " +
"FROM " + DatabaseManager.TABLE_QUANTITY + " AS A JOIN " + DatabaseManager.TABLE_INGREDIENTS + " AS B ON A.ingredient = B.ingredient_name " +
"JOIN " + DatabaseManager.TABLE_PLAN_RECIPES + " AS C ON A.recipe = C.recipe_name " +
"JOIN " + DatabaseManager.TABLE_MEAL_PLAN + " AS D ON C.id = D.plan_recipe " +
"WHERE D.plan_name LIKE ? GROUP BY A.ingredient";
c = db.rawQuery(RECIPE_SEARCH, new String[]{"%" + search + "%"});
if (c.moveToFirst()) {
do {
Shopping_List shopping_list = new Shopping_List();
shopping_list.setQuantity(c.getDouble(c.getColumnIndex("quantity")));
shopping_list.setIngredient_name(c.getString(c.getColumnIndex("ingredient_name")));
shopping_list.setIngredient_type(c.getString(c.getColumnIndex("ingredient_type")));
shopping_list.setMeasurement_name(c.getString(c.getColumnIndex("measurement_name")));
shopList.add(shopping_list);
} while (c.moveToNext());
}
c.close();
db.close();
}
Also, your query returns columns that you don't use in the loop, which I did not remove, by you may remove them.

create a java process to generate a idempiere report

I have Postgres that works when on it own, but doesn't work when integrated into java and called on idempiere. I'm looking for suggestion.
I get the ff error:
caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "00"
Position: 1055; State=42601; ErrorCode=0
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:441)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:365)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:143)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:120)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:384)
at jdk.internal.reflect.GeneratedMethodAccessor48.invoke(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.compiere.db.StatementProxy.invoke(StatementProxy.java:130)
at com.sun.proxy.$Proxy11.executeUpdate(Unknown Source)
at org.compiere.util.DB.executeUpdate(DB.java:1039)
at org.compiere.util.DB.executeUpdate(DB.java:898)
at org.compiere.util.DB.executeUpdate(DB.java:885)
at ice.enterprise.base.report.StockAgingReport.createDetailLines(StockAgingReport.java:145)
at ice.enterprise.base.report.StockAgingReport.doIt(StockAgingReport.java:72)
at org.compiere.process.SvrProcess.process(SvrProcess.java:201)
at org.compiere.process.SvrProcess.startProcess(SvrProcess.java:147)
at org.adempiere.util.ProcessUtil.startJavaProcess(ProcessUtil.java:173)
at org.compiere.apps.AbstractProcessCtl.startProcess(AbstractProcessCtl.java:467)
at org.compiere.apps.AbstractProcessCtl.run(AbstractProcessCtl.java:235)
15:21:49.994===========> DataEngine.loadPrintData: null - ERROR: column "levelno" does not exist
Position: 924
SQL=SELECT T_ReportStockAgeing.CurrentCost,T_ReportStockAgeing.Date1,T_ReportStockAgeing_ICE.Description,T_ReportStockAgeing.OnHand,(SELECT NVL(AD_PInstance.Name,'-1') ||'_'|| NVL(CAST (AD_PInstance.AD_PInstance_ID AS Text),'-1') ||'_'|| NVL((SELECT NVL(AD_Process.Name,'-1') ||'_'|| NVL(AD_Process.Value,'-1') FROM AD_Process WHERE AD_PInstance.AD_Process_ID=AD_Process.AD_Process_ID),'-1') FROM AD_PInstance WHERE T_ReportStockAgeing.AD_PInstance_ID=AD_PInstance.AD_PInstance_ID) AS AAD_PInstance_ID,T_ReportStockAgeing.AD_PInstance_ID AS AD_PInstance_ID,T_ReportStockAgeing.ProductCode,T_ReportStockAgeing.Qty1,T_ReportStockAgeing.Qty2,T_ReportStockAgeing.Qty3,T_ReportStockAgeing.Qty4,T_ReportStockAgeing.Value1,T_ReportStockAgeing.Valu2,T_ReportStockAgeing.Value3,T_ReportStockAgeing.Value4,T_ReportStockAgeing_ICE.T_ReportStockAgeing_ICE_UU,LevelNo FROM T_ReportStockAgeing_ICE WHERE T_ReportStockAgeing_ICE.AD_PInstance_ID=2109500 [136]
15:21:50.030===========> AbstractProcessDialog.doRun: org.postgresql.util.PSQLException: ERROR: column "levelno" does not exist
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.logging.Level;
import org.compiere.print.MPrintFormat;
import org.compiere.process.ProcessInfoParameter;
import org.compiere.process.SvrProcess;
import org.compiere.util.DB;
import org.compiere.util.Env;
import org.compiere.util.Ini;
public class StockAgingReport extends SvrProcess {
private int p_AD_Org_ID = 0;
private int p_AD_Client_ID = 0;
private int p_C_AcctSchema_ID = 0;
private int p_M_Product_Category_ID = 0;
private Timestamp p_Date = null;
private long m_start = System.currentTimeMillis();
#Override
protected void prepare() {
StringBuffer sb = new StringBuffer ("Record_ID=")
.append(getRecord_ID());
// Parameter
ProcessInfoParameter[] para = getParameter();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null && para[i].getParameter_To() == null)
;
else if (name.equals("Date"))
{
p_Date = (Timestamp)para[i].getParameter();
}
else if (name.equals("AD_Org_ID"))
p_AD_Org_ID = ((BigDecimal)para[i].getParameter()).intValue();
else if (name.equals("AD_Client_ID"))
p_AD_Client_ID = para[i].getParameterAsInt();
else if (name.equals("C_AcctSchema_ID"))
p_C_AcctSchema_ID = para[i].getParameterAsInt();
else if (name.equals("M_Product_Category_ID"))
p_M_Product_Category_ID = para[i].getParameterAsInt();
else
log.log(Level.SEVERE, "Unknown Parameter: " + name);
}
log.fine(sb.toString());
}
#Override
protected String doIt() throws Exception {
createDetailLines();
int AD_PrintFormat_ID = DB.getSQLValue(get_TrxName(), "Select AD_PrintFormat_ID from AD_PrintFormat Where name = 'Stock_Ageing'");
if (AD_PrintFormat_ID > 0) {
if (Ini.isClient())
getProcessInfo().setTransientObject (MPrintFormat.get (getCtx(), AD_PrintFormat_ID, false));
else
getProcessInfo().setSerializableObject(MPrintFormat.get (getCtx(), AD_PrintFormat_ID, false));
}
if (log.isLoggable(Level.FINE)) log.fine((System.currentTimeMillis() - m_start) + " ms");
return "";
}
private void createDetailLines() {
StringBuffer sb = new StringBuffer ("INSERT INTO T_ReportStockAgeing "
+ "(AD_PInstance_ID, AD_Client_ID, AD_Org_ID, ProductCode, Description, CurrentCost,"
+ " Qty1, Qty2, Qty3, Qty4, OnHand,"
+ " Value1, Valu2, Value3 ,Value4) ");
sb.append("SELECT ").append(getAD_PInstance_ID()).append(", ").append(Env.getAD_Client_ID(getCtx())).append(", ").append(Env.getAD_Org_ID(getCtx())).append(", ")
.append( "ProductCode, Description, Case OnHand WHEN 0 THEN 0 ELSE CurrentCost*OnHand END AS CurrentCost,"
+ "Qty1, Qty2, Qty3, Qty4, OnHand,"
+ "CASE OnHand WHEN 0 THEN 0 ELSE round((CurrentCost) * Qty1,2) END as Value1, "
+ "CASE OnHand WHEN 0 THEN 0 ELSE round((CurrentCost) * Qty2,2) END as Valu2, "
+ "CASE OnHand WHEN 0 THEN 0 ELSE round((CurrentCost) * Qty3,2) END as Value3, "
+ "CASE OnHand WHEN 0 THEN 0 ELSE round((CurrentCost) * Qty4,2) END as Value4 "
+ "FROM ( "
+ "SELECT "
+ "prod.value as ProductCode, "
+ "prod.description as Description, "
+ "M_Product_Category_ID, "
+ "(SELECT COALESCE (max(c.CurrentCostPrice),0) FROM M_Cost c WHERE c.AD_Org_ID =" +p_AD_Org_ID +" AND c.C_AcctSchema_ID= "+p_C_AcctSchema_ID+" AND prod.M_Product_ID = c.M_Product_ID AND prod.ProductType !='A' ) as CurrentCost, "
+ "(SELECT COALESCE (SUM (st.qtyonhand),0)FROM M_Storage st "
+ "WHERE prod.M_Product_ID = st.M_Product_ID "
+ "AND st.DateMaterialPolicy >= ( ("+p_Date+"::date) - interval '3 month' ) "
+ "AND st.DateMaterialPolicy <= ("+p_Date+"::date) "
+ "AND st.AD_Org_ID = "+p_AD_Org_ID+" AND prod.ProductType !='A' "
+ ") as Qty1, "
+ "(SELECT COALESCE (SUM (st.qtyonhand),0)FROM M_Storage st "
+ "WHERE prod.M_Product_ID = st.M_Product_ID "
+ "AND st.DateMaterialPolicy >= ("+p_Date+"::date- interval '6 month' ) "
+ "AND st.DateMaterialPolicy <= ("+p_Date+"::date - interval '3 month') "
+ "AND st.AD_Org_ID = "+p_AD_Org_ID+" AND prod.ProductType !='A') "
+ "as Qty2, "
+ "(SELECT COALESCE (SUM (st.qtyonhand),0)FROM M_Storage st "
+ "WHERE prod.M_Product_ID = st.M_Product_ID "
+ "AND st.DateMaterialPolicy >= ("+p_Date+"::date - interval '12 month' ) "
+ "AND st.DateMaterialPolicy <= ("+p_Date+"::date- interval '6 month') "
+ "AND st.AD_Org_ID = "+p_AD_Org_ID+" AND prod.ProductType !='A' "
+ ") as Qty3, "
+ "(SELECT COALESCE (SUM (st.qtyonhand),0)FROM M_Storage st "
+ "WHERE prod.M_Product_ID = st.M_Product_ID "
+ "AND st.DateMaterialPolicy < ("+p_Date+"::date- interval '12 month') "
+ "AND st.AD_Org_ID = "+p_AD_Org_ID+" AND prod.ProductType !='A' "
+ ") as Qty4, "
+ "(SELECT COALESCE (SUM (st.qtyonhand),0)FROM M_Storage st "
+ "WHERE prod.M_Product_ID = st.M_Product_ID "
+ "AND st.AD_Org_ID = "+p_AD_Org_ID+" AND prod.ProductType !='A' "
+ ") as OnHand "
+ "FROM M_Product prod "
+ "LEFT JOIN AD_Org org ON org.AD_Org_ID = "+p_AD_Org_ID+" "
+ "LEFT JOIN M_Product_Category prodcat ON prodcat.M_Product_Category_ID = "+p_M_Product_Category_ID+" AND prodcat.AD_Client_ID = "+p_AD_Client_ID+" "
+ "WHERE prod.M_Product_Category_ID = "+ p_M_Product_Category_ID+" AND prod.ProductType !='A' "
+ ")temp ");
sb.append(" ) as temp ");
int no = DB.executeUpdate(sb.toString(), get_TrxName());
log.fine("#" + no);
log.finest(sb.toString());
}
}
I tried to integrate your class example for testing in iDempiere, but as GhostCat pointed, it's better if you create a minimal reproducible example, and also very important, please post also the error that is being thrown by the system, in UI and/or in console log.
The class doesn't have some imports, all the variables are not used, and the private method createDetailLines is never called, I assume the error you're mentioning is in that method, but there is no way to know if is not called.
Now, reviewing the SQL, there are two things to notice:
1 - it's not formatted for java, you use "AND c.C_AcctSchema_ID= $P{C_AcctSchema_ID}" and that's not the way as java manage variables, that sounds like jasper report syntax instead of java. For JDBC you must use ? as a replacement for binding variables
2 - iDempiere is multi-database, the way how the system is designed is to write oracle compatible SQL syntax, and there is a translation layer that converts the oracle statement ot postgresql syntax. So, it's better to avoid using postgresql specific syntax like "::date" or interval '3 month' - it could work, but it can also have problems with the convert layer. If you want to use specific postgresql syntax and avoid the convert layer being confused you can surround the postgresql specific syntax with NATIVE_PostgreSQL_KEYWORK - please don't blame me about the error in this constant :-)

How to Compare date in Prepared statement

I have Sybase Statement which is mentioned below :
select s.airbill_nbr, s.orig, s.dest,p.swa_acct_nbr, s.prod_type, s.outbnd_date, s.shppr_name, s.consgn_name,s.shipping_chrg, s.misc_chrg, s.decl_val_chrg, s.tax_amt, s.fuel_chrg, s.scrty_chrg, s.tot_chrgs, s.tot_pcs, s.tot_chrgbl_wt, s.tot_actl_wt from shipment s, shipment_outbnd_stn o, payment p
where s.sa_shpmt_nbr = o.sa_shpmt_nbr
and o.sa_shpmt_nbr = p.sa_shpmt_nbr
and o.outbnd_date=convert(date,'01/29/2015',101)
and s.outbnd_empl_id is not null
and p.fop_cd = 'SW'
and p.swa_acct_nbr =40584
and s.void_flag is null
I have to create a prepared statement for the above code in Java and I have created the below One :
String variable1="29/01/2015";
psRetrieveAwbData = cattsDbc.prepareStatement( "select s.airbill_nbr, s.orig, s.dest, " +
"p.swa_acct_nbr, s.prod_type, s.outbnd_date, s.shppr_name, s.consgn_name, " +
"s.shipping_chrg, s.misc_chrg, s.decl_val_chrg, s.tax_amt, s.fuel_chrg, " +
"s.scrty_chrg, s.tot_chrgs, s.tot_pcs, s.tot_chrgbl_wt, s.tot_actl_wt " +
"from shipment s, shipment_outbnd_stn o, payment p " +
"where s.sa_shpmt_nbr = o.sa_shpmt_nbr " +
"and o.sa_shpmt_nbr = p.sa_shpmt_nbr " +
"and o.outbnd_date = '"+ variable1 +"'" +
"and s.outbnd_empl_id is not null " +
"and p.fop_cd = 'SW' " +
"and p.swa_acct_nbr = " + iAccount +
"and s.void_flag is null" );
but I dont know how to put date in date Format because the way I have put it is not working by taking the variable1, as variable1 It is taking as String and not finding out the Solution.Could you please tell me how to create the prepared statement where I can directly put date or put the date by storing it in some variable.
PreparedStatement pstmt = con.prepareStatement("select s.airbill_nbr, s.orig, s.dest, " +
"p.swa_acct_nbr, s.prod_type, s.outbnd_date, s.shppr_name, s.consgn_name, " +
"s.shipping_chrg, s.misc_chrg, s.decl_val_chrg, s.tax_amt, s.fuel_chrg, " +
"s.scrty_chrg, s.tot_chrgs, s.tot_pcs, s.tot_chrgbl_wt, s.tot_actl_wt " +
"from shipment s, shipment_outbnd_stn o, payment p " +
"where s.sa_shpmt_nbr = o.sa_shpmt_nbr " +
"and o.sa_shpmt_nbr = p.sa_shpmt_nbr " +
"and o.outbnd_date = ?" +
"and s.outbnd_empl_id is not null " +
"and p.fop_cd = 'SW' " +
"and p.swa_acct_nbr = " + iAccount +
"and s.void_flag is null" );");
pstmt.setDate (dt);

JAVA Persistance OrderBy before a GroupBy

we need to get the last post message group by a transmitter.
Query query = em.createQuery("SELECT m FROM Message m " +
"JOIN m.transmitter " +
"JOIN m.recipient " +
"WHERE m.transmitter = :u1 " +
"OR m.recipient = :u1 " +
"GROUP BY m.recipient,m.transmitter " +
"ORDER BY m.sendDate DESC");
query.setParameter("u1", actualUser);
but we need something like this where we get the oldest message:
Query query = em.createQuery("SELECT m FROM Message m " +
"JOIN m.transmitter " +
"JOIN m.recipient " +
"WHERE m.transmitter = :u1 " +
"OR m.recipient = :u1 " +
"ORDER BY m.sendDate DESC"
"GROUP BY m.recipient,m.transmitter ");
query.setParameter("u1", actualUser);
Thanks for help sorry for my English.
My solution is to get all contact first and then get the last send message from a contact (two queries instead of one big.
Maybe like this?
Query query = em.createQuery("SELECT m FROM Message m " +
"WHERE m.sendDate = (" +
"SELECT MAX(m.sendDate) FROM MESSAGE m "
"JOIN m.transmitter t " +
"JOIN m.recipient r " +
"WHERE t = :u1 " +
"OR r = :u1)");
query.setParameter("u1", actualUser);

Categories