How to add if else or case in SQL select statement - sql

This is my SQL query to fetch data from the tables order and user_master
String str = "select od.total, od.invoice_link, od.status, ";
str += "od.order_type, um.name as sender_name, umr.name as receiver_name, ";
str += "umr.twitter_handle as receiver_twitter_handle, um.twitter_handle as sender_twitter_handle ";
str += "from orders od ";
str += "join user_master um on um.id = od.user_id ";
str += "join user_master umr on umr.id = od.receiver_id ";
str += "where user_id = '"+user_id+"' ";
String json = dao.getResultJSON(str);
return json;
In the database there is this column named order_type which contains values like transfer, request and invoice.I need to return "Payment to" into the variable json if the value in the order_type column is 'transfer' and 'Requested from' if the value in the column is 'request'.Just forget about 'invoice' which i mentioned above.These two will be enough for my expected output..
Anyway thanks in advance

Without knowing where payment_to and requested_from are supposed to come from, here is as shot in the dark:
select
od.total
, od.invoice_link
, od.status
, od.order_type
, um.name as sender_name
, umr.name as receiver_name
, um.twitter_handle as sender_twitter_handle
, umr.twitter_handle as receiver_twitter_handle
, case when od.order_type = 'transfer' then od.payment_to else null end as payment_to
, case when od.order_type = 'request' then od.requested_from else null end as requested_from
from orders od
inner join user_master um on um.id = od.user_id
inner join user_master umr on umr.id = od.receiver_id
where user_id = '"+user_id+"'
In the format you posted:
String str = "select";
str += " od.total";
str += " , od.invoice_link";
str += " , od.status";
str += " , od.order_type";
str += " , um.name as sender_name";
str += " , umr.name as receiver_name";
str += " , um.twitter_handle as sender_twitter_handle ";
str += " , umr.twitter_handle as receiver_twitter_handle";
str += " , case when od.order_type = 'transfer' then od.payment_to else null end as payment_to";
str += " , case when od.order_type = 'request' then od.requested_from else null end as requested_from";
str += " from orders od ";
str += " inner join user_master um on um.id = od.user_id ";
str += " inner join user_master umr on umr.id = od.receiver_id ";
str += " where user_id = '"+user_id+"';";
String json = dao.getResultJSON(str);
return json;

select od.total,
od.invoice_link, od.status,
od.order_type,
um.name as sender_name, umr.name as receiver_name,
umr.twitter_handle as receiver_twitter_handle,
um.twitter_handle as sender_twitter_handle
from orders od
join user_master um on um.id = od.user_id
join user_master umr on umr.id = od.receiver_id
where user_id = SOMETHING
is your SQL query dissected out from what appears to be Java. You should understand that SQL deals in tables; that is, it deals in rectangles full of data. Each result set returns a series of rows. Each row in a result set necessarily must have the same columns as the other rows.
You are asking for two different kinds of rows, one with a Payment to column and the other with a Requested from column. The choice of row depends on some data in the row. This is not going to happen in a single query.
You can do something like this, though.
select
...,
CASE WHEN od.order_type='transfer' THEN receiver_twitter_handle ELSE '' END `Payment to`,
CASE WHEN od.order_type='request' THEN sender_twitter_handle ELSE '' END `Requested from`,
...
This will yield the two columns you want in every row of your result set. One, or both, the columns will contain blanks when irrelevant.
The details of these CASE statements can vary among makes of table server, and you haven't disclosed which one you're using, so there may be a mistake here. But you can fix it.

Related

Postgres Left Join ignores row if ManyToOne property is null

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?

SQL query for select statement when certain bind parameters were entered

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);

vb.net - Index was outside the bounds of the array

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.

Union causing Firebird 2.5 query to fail

This SQL (Firebird 2.5, Dialect 1) query works fine when I run it in Database Workbench, but it fails when I run it under IBO Console with:
count of column list and variable list do not match.
These two queries run successfully if I run them alone under IBO console, so I'm inferring that the problem is because of the "Union." The number and types of columns match for the two queries--both return string, smallint, string (IBO console regards this as a memo), string--so Union should be valid (and DB Workbench finds it so). Thinking that maybe the length of the data was different, I tried casting the third column as a VarChar(500) but that didn't help. Looking for ideas as to why this doesn't work since the part of our app that is executing the query is apparently choking on this in the same way that IBO Console is.
Select QBI.TXNID as ID,
Cast (1 as SmallInt) as TransactionType,
("Invoice " || QBI.REFNUMBER || ": $" || round(QBI.SUBTOTAL, 2) || " on " || QBI.TXNDATE || " for " || QBI.CUSTOMERREF_FULLNAME) as description,
case
when (QBI.CLASSREF_LISTID = "") then "Invoice has no class in Quickbooks"
else "Invoice class doesn't match any dept on job " || JA.JOBID
end as Problem
from QBINVOICE QBI
Join JOBACCOUNTINGID JA
on QBI.CUSTOMERREF_LISTID = JA.jobaccountingid
and QBI.SOURCEID = JA.SOURCEID
left Join CHARTOFACCOUNTS CA
on (CA.qblistid = QBI.CLASSREF_LISTID and CA.qbsourceID = QBI.SOURCEID)
and CA.CHARTACCOUNTTYPE = "SYSTEM"
and CA.CHARTFETCH = "Y"
left Join DEPARTMENTJOB DJ
on JA.JOBID = DJ.JobID
and DJ.departmentID = CA.DEPARTMENTID
where DJ.DEPARTMENTID is null
and QBI.TXNDATE >= "02/01/2017"
union all
select
QBELD.TXNLINEID as ID,
Cast (2 as SmallInt) as TransactionType,
QBB.VENDORREF_FULLNAME || " bill on " || QBB.TXNDATE || ": $" || round(QBELD.AMOUNT, 2) || " " || QBELD.ACCOUNTREF_FULLNAME || " expense" as description,
case
when (QBELD.CLASSREF_LISTID = "") then "Expense has no class in Quickbooks"
else "Expense class doesn't match any dept on job " || JA.JOBID
end as Problem
from QBTxnExpenseLineDetail QBELD
JOIN QBBILL QBB
on QBELD.TXNLINEID = QBB.TXNID
and QBELD.SOURCEID = QBB.SOURCEID
Join JOBACCOUNTINGID JA
on QBELD.CUSTOMERREF_LISTID = JA.jobaccountingid
and QBELD.SOURCEID = JA.SOURCEID
left Join CHARTOFACCOUNTS CA
on (CA.qblistid = QBELD.CLASSREF_LISTID and CA.qbsourceID = QBELD.SOURCEID)
and CA.CHARTACCOUNTTYPE = "SYSTEM"
and CA.CHARTFETCH = "Y"
left Join DEPARTMENTJOB DJ
on JA.JOBID = DJ.JobID
and DJ.departmentID = CA.DEPARTMENTID
where DJ.DEPARTMENTID is null
and QBB.TXNDATE >= "02/01/2017"

Understanding join order for 3 or more tables

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