In Spring Boot i have the following query in a PostgreSQL database, to get data from ConfigElement table and set them to the new one ConfigurationReview table. It works properly as expected:
#Query(
"SELECT new xx.xx.xx.dao.ConfigurationReview(r.id, MAX(ce.id) AS configElementId,"
+ " r.checkMethod, r.targetDate, r.endDate, r.sessionDate, SUM(CASE WHEN i.criticality ="
+ " 0 AND i.relation = 0 THEN 1 ELSE 0 END) AS majorFindings, SUM(CASE WHEN i.criticality"
+ " = 1 AND i.relation = 0 THEN 1 ELSE 0 END) AS minorFindings, r.state) FROM"
+ " ConfigElement ce "
+ "LEFT JOIN ce.reviews r ON r.configElement.id = ce.id "
+ "LEFT JOIN r.criteria cr ON cr.review.id = r.id "
+ "LEFT JOIN cr.issues i ON i.criterion.id = cr.id "
+ "WHERE ce.id = :configurationId AND r.id IS NOT NULL GROUP BY r.id")
Page<ConfigurationReview> findConfigurationReviews(
#Param("configurationId") Long configurationId, Pageable pageable);
There was a need to add another property (r.milestone) with a ManyToOne relation, so i added it to the query:
#Query(
"SELECT new xx.xx.xx.dao.ConfigurationReview(r.id, MAX(ce.id) AS configElementId,"
+ " r.checkMethod, r.targetDate, r.endDate, r.sessionDate, SUM(CASE WHEN i.criticality ="
+ " 0 AND i.relation = 0 THEN 1 ELSE 0 END) AS majorFindings, SUM(CASE WHEN i.criticality"
+ " = 1 AND i.relation = 0 THEN 1 ELSE 0 END) AS minorFindings, r.state, r.milestone) FROM"
+ " ConfigElement ce "
+ "LEFT JOIN ce.reviews r ON r.configElement.id = ce.id "
+ "LEFT JOIN r.criteria cr ON cr.review.id = r.id "
+ "LEFT JOIN cr.issues i ON i.criterion.id = cr.id "
+ "WHERE ce.id = :configurationId AND r.id IS NOT NULL GROUP BY r.id")
Page<ConfigurationReview> findConfigurationReviews(
#Param("configurationId") Long configurationId, Pageable pageable);
Here is the milestone entry in ConfigurationReview dao:
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(foreignKey = #ForeignKey(name = "fk_review_milestones_on_milestone_id"))
private Milestone milestone;
With the above changes, it works properly if r.milestone is not null. But when the r.milestone is null, the complete row is ignored in left join.
As a result, if I have 2 r.milestones with data and 2 r.milestones without, the above query returns only two entries instead of four.
The problem appears only if r.milestone is null (because of the ManyToOne relation?). If another property is null, the row is returned properly.
Any idea how can I fix this?
Related
When I try to extract the result of Division 2 Field from table in access database
If I have a value of 0 an error occurs
sqlSTR = "SELECT TBL_Category_Item_File.Item_Org_Price2/TBL_Stocks_Balances.Item_QTY AS ['Price']FROM (((TBL_Category_Item_File INNER JOIN TBL_Suppliers_Product ON TBL_Category_Item_File.Item_ID = TBL_Suppliers_Product.Item_ID) INNER JOIN TBL_Suppliers ON TBL_Suppliers_Product.Supp_ID = TBL_Suppliers.Supp_ID) INNER JOIN TBL_Sub_categories ON TBL_Category_Item_File.ID_Sub_categories = TBL_Sub_categories.ID_Sub_categories) INNER JOIN TBL_Stocks_Balances ON (TBL_Stocks_Balances.Item_ID = TBL_Category_Item_File.Item_ID) AND (TBL_Category_Item_File.Item_BarCode = TBL_Stocks_Balances.Item_Barcode) WHERE tbl_Category_Item_File.Catg_ID =" & Split(cmblist.Text, " - ")(0)
If you are trying to avoid the error, you can use a CASE statement in your query to check for a 0 value in the Item_Org_Price2 field and return a different value if it is 0. For example, you could do something like this:
SELECT
CASE
WHEN TBL_Category_Item_File.Item_Org_Price2 = 0
THEN 0
ELSE TBL_Category_Item_File.Item_Org_Price2/TBL_Stocks_Balances.Item_QTY
END AS ['Price']
FROM (((TBL_Category_Item_File INNER JOIN TBL_Suppliers_Product ON TBL_Category_Item_File.Item_ID = TBL_Suppliers_Product.Item_ID) INNER JOIN TBL_Suppliers ON TBL_Suppliers_Product.Supp_ID = TBL_Suppliers.Supp_ID) INNER JOIN TBL_Sub_categories ON TBL_Category_Item_File.ID_Sub_categories = TBL_Sub_categories.ID_Sub_categories) INNER JOIN TBL_Stocks_Balances ON (TBL_Stocks_Balances.Item_ID = TBL_Category_Item_File.Item_ID) AND (TBL_Category_Item_File.Item_BarCode = TBL_Stocks_Balances.Item_Barcode) WHERE tbl_Category_Item_File.Catg_ID =" & Split(cmblist.Text, " - ")(0)
I need help with a select statement. I want to use this for my search API where if you pass in certain parameters, fist Name, or last Name, or both, or first Name and state, the query will run as other parameters were not filled it.
Is there a way to do that? This is my query
select d.is_purged, d.is_reorg, ds.dlr_nm, ds.city, c.first_nm, c.middle_nm,
c.last_nm, c.is_mdd, ds.state, lds.display_name, c.is_wrn, d.crt_ts, d.upd_ts
from deal d
left join candidate c on d.candidate_id = c.id
left join lkup_deal_status lds on d.status = lds.status
left join dealership ds on d.id = ds.deal_id
where (c.first_nm is null or c.first_nm = :firstName )
and (d.is_purged = false )
and (ds.dlr_nm is null or ds.dlr_nm = :dealershipName)
and (ds.city is null or ds.city = :city)
and (c.middle_nm is null or c.middle_nm = :middleName)
and (c.last_nm is null or c.last_nm = :lastName)
and (ds.state is null or ds.state = :state)
and (lds.display_name is null or lds.display_name = :status)
thanks in advance
I ended up figuing it out.
For Java: String SEARCH_DEAL = "select d.id, ds.id, ds.dlr_nm, d.bac,
d.is_reorg, c
c.first_nm, c.middle_nm, " +
"c.last_nm, c.is_mdd, c.is_wrn, ds.city, ds.state, ds.rgn,
lds.display_name, d.crt_ts, d.upd_ts " +
"from mhdid_171749.deal d left join candidate c on d.candidate_id = c.id
" +
"left join lkup_deal_status lds on d.status = lds.status " +
"left join dealership ds on d.id = ds.deal_id " +
"where d.is_purged = false " +
" and (:dealershipName::varchar is null or ds.dlr_nm = :dealershipName)"
+
" and (:firstName::varchar is null or c.first_nm = :firstName ) " +
" and (:lastName::varchar is null or c.last_nm = :lastName) " +
" and (:bacCode::int is null or d.bac = :bacCode)" +
" and (:city::varchar is null or ds.city = :city) " +
" and (:state::varchar is null or ds.state = :state) " +
" and (:region::varchar is null or ds.rgn = :region) " +
" and (:status::varchar is null or lds.display_name = :status) ";
For SQL:
select d.is_purged, d.is_reorg, ds.dlr_nm, ds.city, c.first_nm,
c.middle_nm,
c.last_nm, c.is_mdd, ds.state, lds.display_name, c.is_wrn, d.crt_ts,
d.upd_ts
from mhdid_171749.deal d
left join candidate c on d.candidate_id = c.id
left join lkup_deal_status lds on d.status = lds.status
left join dealership ds on d.id = ds.deal_id
where d.is_purged = false
and (:firstName is null or c.first_nm = :firstName )
and (:dealershipName is null or ds.dlr_nm = :dealershipName)
and (:city is null or ds.city = :city)
and (:middleName is null or c.middle_nm = :middleName)
and (:lastName is null or c.last_nm = :lastName)
and (:state is null or ds.state = :state)
and (:status is null or lds.display_name = :status);
I got a problem in vb.net. By the way I am a newbie. I need your help
what's problem on this error:
My code:
Public Sub load_stockid_monthly_byUP(ByVal type As Integer, ByVal filter As Integer, ByVal input As String)
Dim sqlquery As String = ""
Dim myCommand As New MySqlCommand
Dim myData As MySqlDataReader
Dim x As Integer = 0
Dim where As String = ""
Dim order As String = ""
If filter = 1 Then
where = ""
ElseIf filter = 2 Then
where = " AND r.type =" & input
ElseIf filter = 3 Then
where = " AND s.cat_id =" & input
ElseIf filter = 4 Then
where = " AND (s.desp like '% " & input & " %' OR s.desp like '" & input & " %' OR s.desp like '% " & input & "' OR s.desp = '" & input & "')"
ElseIf filter = 5 Then
where = " AND (s.cat_id = 1 OR s.cat_id = 2 OR s.cat_id = 4 OR s.cat_id = 5 )"
ElseIf filter = 6 Then
where = " AND (s.pallet_id <> 0 OR s.carton_id <> 0)"
order = " ORDER BY carton_id, pallet_id , stock_id"
ElseIf filter = 7 Then
where = " AND (s.pallet_id <> 0)"
order = " ORDER BY pallet_id , stock_id"
ElseIf filter = 8 Then
where = " AND (s.carton_id <> 0)"
order = " ORDER BY carton_id, stock_id"
ElseIf filter = 9 Then
where = " AND (s.uniform_id <> 0)"
order = " ORDER BY uniform_id"
End If
If type = 1 Then
sqlquery = "(SELECT s.id AS id,s.stock_id AS stock_id ,s.packing_id AS packing_id ,s.carton_id AS carton_id, s.pallet_id AS pallet_id, s.desp AS desp,i.unit_price AS unit_price, i.rate AS rate, c.type AS cat, u.unit AS uom, s.currency AS currency, s.uniform_id As uniform_id FROM incoming AS i LEFT JOIN stock AS s ON i.stock_id = s.id LEFT JOIN uom AS u ON s.uom = u.id LEFT JOIN stock_cat AS c ON s.cat_id = c.id LEFT JOIN supplier AS r ON s.supplier_id = r.id WHERE s.active = 1 AND (i.active = 1 OR i.active = 2)" & where & " GROUP BY c.type, s.stock_id , i.unit_price, i.rate ) UNION " _
& "(SELECT s.id AS id,s.stock_id AS stock_id ,s.packing_id AS packing_id ,s.carton_id AS carton_id, s.pallet_id AS pallet_id,s.desp AS desp,i.unit_price AS unit_price, i.rate AS rate, c.type AS cat, u.unit AS uom, s.currency AS currency, s.uniform_id As uniform_id FROM adjust AS i LEFT JOIN stock AS s ON i.stock_id = s.id LEFT JOIN uom AS u ON s.uom = u.id LEFT JOIN stock_cat AS c ON s.cat_id = c.id LEFT JOIN supplier AS r ON s.supplier_id = r.id WHERE s.active = 1 AND i.adjust_qty > 0 AND (i.active = 1 OR i.active = 2)" & where & " GROUP BY c.type, s.stock_id , i.unit_price, i.rate ) " & order
' sqlquery = "SELECT s.id AS id,s.stock_id AS stock_id ,s.desp AS desp,i.unit_price AS unit_price, i.rate AS rate, c.type AS cat, u.unit AS uom, s.currency AS currency FROM incoming AS i LEFT JOIN stock AS s ON i.stock_id = s.id LEFT JOIN uom AS u ON s.uom = u.id LEFT JOIN stock_cat AS c ON s.cat_id = c.id LEFT JOIN supplier AS r ON s.supplier_id = r.id WHERE (i.active = 1 OR i.active = 2)" & where & " GROUP BY c.type, s.stock_id , i.unit_price ORDER BY c.type ,s.stock_id "
ElseIf type = 2 Then
sqlquery = "SELECT s.id AS id,s.stock_id AS stock_id ,s.desp AS desp,n.unit_price AS unit_price, n.rate AS rate, c.type AS cat, u.unit AS uom, s.currency AS currency FROM issue AS i LEFT JOIN stock AS s ON i.stock_id = s.id LEFT JOIN uom AS u ON s.uom = u.id LEFT JOIN incoming AS n ON i.irm_id = n.id LEFT JOIN stock_cat AS c ON s.cat_id = c.id LEFT JOIN supplier AS r ON s.supplier_id = r.id WHERE s.active = 1 AND i.active = 1" & where & " GROUP BY c.type, s.stock_id , n.unit_price ORDER BY c.type ,s.stock_id"
End If
stock_id_count = 0
ConnectmyDB()
myCommand.Connection = conn
myCommand.CommandText = sqlquery
myData = myCommand.ExecuteReader
If myData.HasRows = False Then
x = 1
Else
While myData.Read
data(x, 0) = myData.GetInt32("id")
data(x, 1) = myData.GetString("stock_id")
data(x, 2) = myData.GetString("desp")
data(x, 8) = myData.GetString("unit_price")
data(x, 9) = myData.GetString ("rate")
data(x, 12) = myData.GetString("cat")
data(x, 14) = myData.GetString("uom")
data(x, 16) = myData.GetString("packing_id")
x = x + 1
End While
End If
DisconnectDatabase()
stock_id_count = x
End Sub 'closing stock unit price
I get the error:
Index was outside the bounds of the array for that code 'data(x, 0) = myData.GetInt32("id")'
How to fix that?
This is what i get when run in program:
************** Exception Text **************
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Purchasing.mdlStoreBalance.load_stockid_monthly_byUP(Int32 type, Int32 filter, String input)
at Purchasing.frmStockBalanceReport.bt_preview_Click(Object sender, EventArgs e)
Thank you
Where is data(x,?) defined? You fill data within a while loop, but there is no checking to see if the while loop overruns the defined bounds.
I also can't tell how much data you expect to read. This will influence the run-time for the while loop and how high x is expected to get.
(would have asked this as a comment, but my rep is not yet high enough in this form).
As an aside, the checking of filter can be done in a select case statement. This will allow you to double check that you have covered where and order consistently. Also, as a coding convention, naming variables exactly the same as a one of your keywords (in this case a SQL keyword) can hide simple errors. Calling them something like whereStmnt and orderStmnt might help.
I have one mysql query like below where I'm using conditional parameter in where clause. How can I rewrite the same in JPA?
SELECT * FROM notification n where if (n.feature_details_id=16, category_id IN (SELECT r.id FROM procurement_category r where r.spendpool_id IN (SELECT spendpool_id FROM procurement_category p where p.id IN (1,4))),category_id IN (4)) and (recipient =76 or n.recipient_type = 'ALL' and n.id NOT IN (select ns.notification_id from notification_statistics ns where ns.user_id =76 and ns.status = 'DISMISSED') and n.sender != 76);
I've tried this. It only works when passing single value to param categoryIds.
#Query("select n from Notification n "
+ "where (n.category.id IN(case when n.featureDetails.id=2 then(SELECT r.id FROM ProcurementCategory r where r.spendpoolId.id IN "
+ "(SELECT p.spendpoolId.id FROM ProcurementCategory p where p.id IN (:categoryIds))) "
+ "else (:categoryIds) end )) "
+ "and n.recipient =:recipient "
+ "or n.recipientType = 'ALL' "
+ "and n.category.id IN (SELECT r.id FROM ProcurementCategory r where r.spendpoolId.id IN "
+ "(SELECT p.spendpoolId.id FROM ProcurementCategory p where p.id IN (:categoryIds))) "
+ "and n.id NOT IN (select ns.notification.id from NotificationStatistics ns where ns.user.id =:recipient and ns.status = 'DISMISSED') "
+ "and n.sender != :recipient " )
If passing multiple values it gives error like
05-11-2016 09:58:32.153 [http-nio-8080-exec-3] ERROR o.h.e.jdbc.spi.SqlExceptionHelper - Operand should contain 1 column(s)
05-11-2016 09:58:32.154 [http-nio-8080-exec-3] DEBUG c.b.i.aop.logging.LoggingAspect - Enter: com.beroe.insync2.web.rest.errors.ExceptionTranslator.dataIntegrityViolationException() with argument[s]
I have an old query that was using *= operator. Right now, the query has where clause like below
Table1.Column1 *= Table2.Column1
AND Table1.Column2 *= Table3.Column1
if (some conditions in C# script) //this whole clause is generated by C# function based on different conditions
AND Table1.Column3 *= Table4.Column1
I have to rewrite it to use left join, because well, we are not dinosaurs anymore, and are moving to SQL server 2014 (from sql server 2000). Anyway, I have rewritten the query like
From Table1
Left Join Table2 On Table1.Column1 = Table2.Column1
Left Join Table3 On Table1.Column2 = Table3.Column1
Left Join Table4 On Table1.Column3 = Table4.Column1
I believe this should provide me the same resultset, but it is not. Clearly SQL Server is not following the same join order in both cases. So, I have to figure out the exact order the old query is following, and how to recreate the same order.
P.S. I don't have much understanding about the code. But, I can post the complete function here, in case if it helps someone understand the situation better.
Edit:
The exact query builder function, I am using.
public virtual FANUC.Common.BaseClasses.Row[] GetCustomersForPopup( FANUC.Common.BaseClasses.Row objListCustomerFilter, FANUC.Common.BaseClasses.PagingEventArgs e ) {
string strConnector = " WHERE ";
string strANDClause = "";
string strSQLQuery = " SELECT "
+ " TBL_Company_Master.CMPM_Company_ID,"
+ " TBL_Company_Master.CMPM_Company_Name,"
+ " " + ( ( FANUCUser )Thread.CurrentPrincipal.Identity ).DBUser + ".fnGetRefCodeValue( CMPM_Company_Type_ID ) AS CMPM_CompanyTypeID,"
+ " TBL_Company_Master.CMPM_Company_NickName,"
+ " TBL_Company_Master.CMPM_Service_Center_ID,"
+ " TBL_Company_Master.CMPM_Company_BranchName,"
+ " TBL_Company_Master.CMPM_Black_Listed_Flag,"
+ " TBL_Company_Master.CMPM_Prohibited_Company_Flag,"
+ " " + ( ( FANUCUser )Thread.CurrentPrincipal.Identity ).DBUser + ".fnGetRefCodeValue( TBL_Company_Master.CMPM_Status ) AS CMPM_Status,"
+ " TBL_Company_Master.CMPM_City_Location_ID AS CMPM_City_Location_ID,"
+ " TBL_City_Location_Master.CLIM_City_Name AS CLIM_City_Name, "
+ " TBL_Company_Master.CMPM_Country_ID AS CMPM_Country_ID,"
+ " TBL_Country_Master.CRIM_CountryName, "
+ " TBL_Company_Master.CMPM_Night_Call_Applicable_flag,"
+ " TBL_Company_Master.CMPM_Default_currency_for_transaction,"
+ " TBL_Company_Master.CMPM_Telephone_No, "
+ " TBL_Customer_Contact_Master.CNTM_ContactPersonName, "
+ " TBL_Customer_Contact_Master.CNTM_Section_Name, "
+ " TBL_Company_Master.Use_Count, "
+ " TBL_Company_Master.CMPM_Self_Company_Indicator, "
+ " TBL_Company_Master.CMPM_Transport_Time ";
string strFromClause = " FROM TBL_Company_Master, "
+ " TBL_Service_Center_Master, "
+ " TBL_City_Location_Master, "
+ " TBL_Country_Master, "
+ " TBL_Customer_Contact_Master";
strANDClause += " AND TBL_Company_Master.CMPM_Service_Center_ID *= TBL_Service_Center_Master.SCRM_Service_Center_ID "
+ " AND TBL_Company_Master.CMPM_City_Location_ID *= TBL_City_Location_Master.CLIM_City_ID "
+ " AND TBL_Company_Master.CMPM_Country_ID *= TBL_Country_Master.CRIM_CountryID ";
if ( objListCustomerFilter[ Constants.IS_CALLING_CUSTOMER ] != null || objListCustomerFilter[ Constants.IS_PAYEE_CUSTOMER ] != null || Convert.ToInt32( objListCustomerFilter[ "CUTM_Customer_Type_ID" ] ) == 120 )
strANDClause += " AND TBL_Company_Master.CMPM_Company_ID *= TBL_Customer_Contact_Master.CNTM_Customer_ID ";
else
strANDClause += " AND TBL_Company_Master.CMPM_Company_ID = TBL_Customer_Contact_Master.CNTM_Customer_ID " ;
strANDClause += " AND TBL_Customer_Contact_Master.CNTM_Default_Flag = 'Y' ";
strANDClause += " AND CMPM_Active_Flag != 'N'";
if ( objListCustomerFilter["CUTM_Customer_Type_ID"] != null && Convert.ToString(objListCustomerFilter["CUTM_Customer_Type_ID"]) != "" ) {
strFromClause += " ,TBL_Customer_Type_Mapping ";
strANDClause += " AND CUTM_Customer_ID = CMPM_Company_ID " + " AND CUTM_Customer_Type_ID = "+Convert.ToString(objListCustomerFilter["CUTM_Customer_Type_ID"]);
}
if ( objListCustomerFilter["CMPM_Company_Type_ID"] != null && Convert.ToString(objListCustomerFilter["CMPM_Company_Type_ID"]) != "" && Convert.ToString(objListCustomerFilter["CMPM_Company_Type_ID"]) != Constants.ALL ) {
strANDClause += " AND CMPM_Company_Type_ID IN ("+Convert.ToString(objListCustomerFilter["CMPM_Company_Type_ID"])+","+Constants.COMPANY_TYPE_BOTH+") ";
}
if ( !Convert.ToString( objListCustomerFilter[ Constants.PAYMENT_REQD ] ).Equals(Constants.CONST_NO ) ) {
strSQLQuery += ", TBL_Company_Payment_Terms.CMPT_Payment_Term_Description "
+ ", TBL_Company_Payment_Terms.CMPT_Payment_Term_ID ";
strFromClause += " ,TBL_Company_Payment_Terms ";
if((objListCustomerFilter[Constants.IS_CALLING_CUSTOMER] != null) ||(objListCustomerFilter[Constants.IS_END_USER] != null) )
strANDClause += " AND TBL_Company_Master.CMPM_Company_ID *= TBL_Company_Payment_Terms.CMPT_Company_ID "
+ " AND TBL_Company_Payment_Terms.CMPT_Default = 'Y' ";
else
strANDClause += " AND TBL_Company_Master.CMPM_Company_ID = TBL_Company_Payment_Terms.CMPT_Company_ID "
+ " AND TBL_Company_Payment_Terms.CMPT_Default = 'Y' ";
if ( objListCustomerFilter[ "CMPM_Company_Type_ID" ] != null && Convert.ToString( objListCustomerFilter[ "CMPM_Company_Type_ID" ] ) != Constants.COMPANY_TYPE_BOTH && Convert.ToString( objListCustomerFilter[ "CMPM_Company_Type_ID" ] ) != Constants.ALL )
strANDClause += " AND CMPT_Company_Type_ID = " + Convert.ToString( objListCustomerFilter[ "CMPM_Company_Type_ID" ] );
}
strANDClause += " AND CMPM_Subsidiary_Code = '"+((FANUCUser)Thread.CurrentPrincipal.Identity).SubsidiaryCode+"'";
Row objFilter = new Row();
objFilter["CMPM_Company_ID"] = objListCustomerFilter["CMPM_Company_ID"];
objFilter["CMPM_Black_Listed_Flag"] = objListCustomerFilter["CMPM_Black_Listed_Flag"];
objFilter["CMPM_Prohibited_Company_Flag"] = objListCustomerFilter["CMPM_Prohibited_Company_Flag"];
objFilter["CMPM_Status"] = objListCustomerFilter["CMPM_Status"];
objFilter["CMPM_Company_Name~like"] = objListCustomerFilter["CMPM_Company_Name"];
objFilter["CMPM_Company_NickName~like"] = objListCustomerFilter["CMPM_Company_NickName"];
objFilter["CMPM_Telephone_No~like"] = objListCustomerFilter["CMPM_Telephone_No"];
objFilter["CMPM_FAX_No"] = objListCustomerFilter["CMPM_FAX_No"];
objFilter["CMPM_Service_Center_ID"] = objListCustomerFilter["CMPM_Service_Center_ID"];
objFilter["CMPM_Billing_Company_ID"] = objListCustomerFilter["CMPM_Billing_Company_ID"];
objFilter["CMPM_Shipping_Company_ID"] = objListCustomerFilter["CMPM_Shipping_Company_ID"];
objFilter["CMPM_City_Location_ID"] = objListCustomerFilter["CMPM_City_Location_ID"];
objFilter["CMPM_State_ID"] = objListCustomerFilter["CMPM_State_ID"];
objFilter["CMPM_Country_ID"] = objListCustomerFilter["CMPM_Country_ID"];
objFilter["CMPM_Grp_Parent_Company_ID"] = objListCustomerFilter["CMPM_Grp_Parent_Company_ID"];
objFilter["CMPM_Night_Call_Applicable_Flag"] = objListCustomerFilter["CMPM_Night_Call_Applicable_Flag"];
objFilter["CMPM_Default_currency_for_transaction"] = objListCustomerFilter["CMPM_Default_currency_for_transaction"];
objFilter["CMPM_Company_local_registration_No~like"] = objListCustomerFilter["CMPM_Company_local_registration_No"];
objFilter["CMPM_Company_central_registration_No~like"] = objListCustomerFilter["CMPM_Company_central_registration_No"];
objFilter["CMPM_Insurance_Policy_No~like"] = objListCustomerFilter["CMPM_Insurance_Policy_No"];
objFilter["CMPM_Active_Flag"] = objListCustomerFilter["CMPM_Active_Flag"];
objFilter["CMPM_Company_BranchName~like"] = objListCustomerFilter["CMPM_Company_BranchName"];
objFilter["CMPM_Company_BranchName_LocalLanguage~like"] = objListCustomerFilter["CMPM_Company_BranchName_LocalLanguage"];
objFilter["CMPM_Postal_Code"] = objListCustomerFilter["CMPM_Postal_Code"];
objFilter["CMPM_Web_Site~like"] = objListCustomerFilter["CMPM_Web_Site"];
objFilter["CMPM_Distance"] = objListCustomerFilter["CMPM_Distance"];
if ( objListCustomerFilter["CMPM_Self_Company_Indicator"] != null && Convert.ToString(objListCustomerFilter["CMPM_Self_Company_Indicator"]) != Constants.ALL )
objFilter[ "CMPM_Self_Company_Indicator" ] = objListCustomerFilter["CMPM_Self_Company_Indicator"];
CommonBQ objCommonBQ = new CommonBQ();
string strSearchClause = objCommonBQ.CreateFilter( objFilter );
string strFinalString = "";
if ( !strSearchClause.Equals( "" ) ) strFinalString = strSQLQuery + strFromClause + strConnector + strSearchClause + strANDClause;
else {
strSQLQuery += strFromClause + strConnector + strANDClause;
int iFirstPos = strSQLQuery.IndexOf( "AND", 0 );
string strFirstPart = strSQLQuery.Substring( 0, iFirstPos );
string strSecondPart = strSQLQuery.Substring( iFirstPos + 3, strSQLQuery.Length - iFirstPos - 3 );
strFinalString = strFirstPart + strSecondPart;
}
return GetRows( strFinalString, CreateParameterArray( objListCustomerFilter ), CommandType.Text, null, e );
}
There are a few things you should update in this query:
Use Table Alias in select clause instead of complete table names.
TBL_Customer_Contact_Master is being joined based on condition:
objListCustomerFilter[ Constants.IS_CALLING_CUSTOMER ] != null ||
objListCustomerFilter[ Constants.IS_PAYEE_CUSTOMER ] != null ||
Convert.ToInt32( objListCustomerFilter[ "CUTM_Customer_Type_ID" ] )
== 120 ) If this holds true then there's a Left Join else Inner join.
So update the statements as:
string strFromClause =
" FROM TBL_Company_Master TCM " +
" Left Join TBL_Service_Center_Master TSC on
TCM.CMPM_Service_Center_ID = TSC.SCRM_Service_Center_ID " +
"Left Join TBL_City_Location_Master TCL on
TCM.CMPM_City_Location_ID = TCL.CLIM_City_ID " +
"Left Join TBL_Country_Master TC on
TCM.CMPM_Country_ID = TC.CRIM_CountryID ";
Update condition 1 as:
if ( objListCustomerFilter[ Constants.IS_CALLING_CUSTOMER ] != null ||
objListCustomerFilter[ Constants.IS_PAYEE_CUSTOMER ] != null || Convert.ToInt32(
objListCustomerFilter[ "CUTM_Customer_Type_ID" ] ) == 120 )
strFromClause += " Left join TBL_Customer_Contact_Master TCCM on TCM.CMPM_Company_ID
= TCCM.CNTM_Customer_ID ";
else
strFromClause += " Inner join TBL_Customer_Contact_Master TCCM on TCM.CMPM_Company_ID
= TCCM.CNTM_Customer_ID ";
Then update condition 2 as:
if ( objListCustomerFilter["CUTM_Customer_Type_ID"] != null && Convert.ToString
(objListCustomerFilter["CUTM_Customer_Type_ID"]) != "" ) {
strFromClause += "Left join TBL_Customer_Type_Mapping on CUTM_Customer_ID = CMPM_Company_ID AND CUTM_Customer_Type_ID = "+Convert.ToString(objListCustomerFilter["CUTM_Customer_Type_ID"] ; }
And condition 3 as:
if((objListCustomerFilter[Constants.IS_CALLING_CUSTOMER] != null) ||(objListCustomerFilter
[Constants.IS_END_USER] != null) )
strFromClause += " Left Join TBL_Company_Payment_Terms TCPT
On TCM.CMPM_Company_ID = TCPT.CMPT_Company_ID AND TCPT.CMPT_Default = 'Y' ";
else
strFromClause += " Inner Join TBL_Company_Payment_Terms TCPT
On TCM.CMPM_Company_ID = TCPT.CMPT_Company_ID AND TCPT.CMPT_Default = 'Y' ";
I might have missed a few commas and semi - colons here and there but it should give you an idea where things might be missing. Hope this helps!!!
The order doesn't matter in left outer joins so please stay assured, it's not causing it. My guess would be the if statments might be causing the difference in results.
If you can share the table data or the outputs, it could be figured out.
The difference is in how additional where clause filters are applied for columns in the outer joined tables.
With this:
select *
from a
left outer join b on a.id = b.id
where
b.other_col = 'test'
The result will contain only rows where the row in b was found and the other_col column in b has the value test.
Comparing to this:
select *
from a, b
where
a.id *= b.id
and b.other_col = 'test'
This will find all rows in a. And it will include the columns from b for rows where b.other_col = 'test'.
So taking the second query and converting it to one with a left join, one of the following would give the same output:
-- 1.
select *
from a
left outer join b on a.id = b.id and b.other_col = 'test'
-- 2.
select *
from a
left outer join
(
select *
from b
where other_col = 'test'
) as b on a.id = b.id