Understanding join order for 3 or more tables - sql

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

Related

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

how to optimized sql query for speed up performance

i just have one sub query that just retrieves thousands of rows. here is my query :
str = "select * from ";
str += " (SELECT a.[ID] ,a.[strUserName], ";
str += " (select intCurrentBalance from accountmappings where intUserID = a.[ID] and intAccountType = 1) as Prm_Balance ";
str += " ,(select intCurrentBalance from accountmappings where intUserID = a.[ID] and intAccountType = 2 ) as Trn_Balance ";
str += " ,(select intCurrentBalance from accountmappings where intUserID = a.[ID] and intAccountType = 3 ) as Opt_Balance ";
str += " ,a.[strMobile] ";
str += " ,a.[strEmailID] ";
str += " ,a.[bIsApproved] ";
str += " ,a.[bIsActive] ";
str += " ,a.[dtlastrecharge] ";
str += " ,case when b.id is null then 0 else b.id end as createdbyId ";
str += " ,case when b.strusername is null then '' else b.strusername end as createdby ";
str += " FROM users a left join users b on a.intCreatedBy = b.ID ";
str += " ) as test ";
str += " where Prm_Balance < " + int.Parse(txt_balance.Text.Trim()) + " and Trn_Balance < " + int.Parse(txt_balance.Text.Trim()) + " and Opt_Balance < " + int.Parse(txt_balance.Text.Trim());
but this query takes too much time to display data. what resolution for this.
You can use single join for multiple account type and use CASE in the column selection as below
str = "select * from ";
str += " (SELECT a.[ID] ,a.[strUserName], ";
str += " CASE WHEN am.intAccountType = 1 THEN am.intCurrentBalance ELSE 0 END as Prm_Balance ";
str += " ,CASE WHEN am.intAccountType = 2 THEN am.intCurrentBalance ELSE 0 END as Trn_Balance ";
str += " ,CASE WHEN am.intAccountType = 3 THEN am.intCurrentBalance ELSE 0 END as Opt_Balance ";
str += " ,a.[strMobile] ";
str += " ,a.[strEmailID] ";
str += " ,a.[bIsApproved] ";
str += " ,a.[bIsActive] ";
str += " ,a.[dtlastrecharge] ";
str += " ,case when b.id is null then 0 else b.id end as createdbyId ";
str += " ,case when b.strusername is null then '' else b.strusername end as createdby ";
str += " FROM users a left join users b on a.intCreatedBy = b.ID ";
str += " left join accountmappings am ON am.intUserID = a.id
AND am.intAccountType in (1,2,3) ";
str += " ) as test ";
str += " where Prm_Balance < " + int.Parse(txt_balance.Text.Trim()) + " and Trn_Balance < " + int.Parse(txt_balance.Text.Trim()) + " and Opt_Balance < " + int.Parse(txt_balance.Text.Trim());
One obvious improvement is to remove subqueries and use them in the left joins as follows:
str = "select * from ";
str += " (SELECT a.[ID] ,a.[strUserName], ";
str += " a1.intCurrentBalance as Prm_Balance ";
str += " ,a2.intCurrentBalance as Trn_Balance ";
str += " ,a3.intCurrentBalance as Opt_Balance ";
str += " ,a.[strMobile] ";
str += " ,a.[strEmailID] ";
str += " ,a.[bIsApproved] ";
str += " ,a.[bIsActive] ";
str += " ,a.[dtlastrecharge] ";
str += " ,case when b.id is null then 0 else b.id end as createdbyId ";
str += " ,case when b.strusername is null then '' else b.strusername end as createdby ";
str += " FROM users a left join users b on a.intCreatedBy = b.ID ";
str += " left join accountmappings a1 on (a1.intUserID = a.[ID] and a1.intAccountType = 1) ";
str += " left join accountmappings a2 on (a2.intUserID = a.[ID] and a2.intAccountType = 2) ";
str += " left join accountmappings a3 on (a3.intUserID = a.[ID] and a3.intAccountType = 3) ";
str += " ) as test ";
str += " where Prm_Balance < " + int.Parse(txt_balance.Text.Trim()) + " and Trn_Balance < " + int.Parse(txt_balance.Text.Trim()) + " and Opt_Balance < " + int.Parse(txt_balance.Text.Trim());
Cheers!!

how to get only first row of datatable with modified specific row value

I have query to just summary of total no of jobs running. now I just want some specific result if there is unique rows found like unique category id with assign job then ok with multiple record set. but no category found if is null then just only pass first record from datatable with modified text with 'ALL' as category name. can we achieve this result.
here is my query and some operations I'm doing with them.
string str = "";
DataTable dt = new DataTable();
str = "SELECT j.[JobID], p.[Id] As PreparedEmailID,p.[Title] AS 'PreparedEmailName',j.[CreatedOn],j.[CompletedOn],j.CategoryID,j.[SubscriberCount],j.[EmailsSent],c.[CategoryName] As SubscriberCategory,(SELECT TOP 1 [Message] FROM [LoggedMessages] WHERE [JobID] =j.[JobID] ORDER BY [LoggedMessageID] DESC) AS 'LoggedMessage',(SELECT [Name] FROM tbl_User_master u WHERE u.Id =j.UserID) As CreatedBy FROM [Jobs] AS j INNER JOIN [tbl_Email_master] AS p ON p.[Id] = j.[PreparedEmailID] INNER JOIN [tbl_User_master] AS u ON u.[Id]=j.[UserID] INNER JOIN tbl_Categories c ON c.Id = j.CategoryID OR (c.Id IS NOT NULL AND j.CategoryID IS NULL) where 1=1 ";
if (chk_date.Checked == true)
{
str += " and ( [CreatedOn] between '" + CommonLogic.Get_Date_From_String(txt_date_from.Text, 1);
str += "' and '" + CommonLogic.Get_Date_From_String(txt_date_to.Text, 2) + "' )";
}
if (string.IsNullOrEmpty(txttitle.Text.Trim()))
{
str += string.Empty;
}
else
{
str += " and p.Title like '%" + txttitle.Text.Trim() + "%'";
}
if (ddl_fromuser.SelectedItem.Text.ToString() == ".All")
{
str += string.Empty;
}
else
{
str += " and j.FromuserID = CONVERT(INT," + Convert.ToInt32(ddl_fromuser.SelectedValue.ToString()) + ")";
}
if (ddl_subcategories.SelectedItem.Text.ToString() == ".All")
{
str += string.Empty;
}
else
{
str += " and j.CategoryID = CONVERT(INT," + Convert.ToInt32(ddl_subcategories.SelectedValue.ToString()) + ")";
}
dt = obj.Get_Data_Table_From_Str(str);
if (dt.Rows.Count > 1)
{
dt.Rows[0]["SubscriberCategory"] = "ALL";
var topRows = dt.AsEnumerable().FirstOrDefault();
egrd.DataSource = topRows;
egrd.DataBind();
}
else
{
egrd.DataSource = dt;
egrd.DataBind();
}
ViewState["data"] = dt;
how ever this gives me error like no JobID found to this record set. whether it is still exists in record set.
please help me...
well I tried this solution but no success...……..
if (dt.Rows.Count > 1)
{
dt.Rows[0]["SubscriberCategory"] = "ALL";
var topRows = dt.AsEnumerable().GroupBy(j => j.Field<int>("JobID")).Select(j => j.First()).ToList();
egrd.DataSource = topRows;
egrd.DataBind();
}
it's gives me exception like DataBinding: 'System.Data.DataRow' does not contain a property with the name 'JobID'.
Just replace .ToList() with .CopyToDataTable() resolve my problem

Multiples statements where clause with differents values in Sql using JPA

Hi guys I´m doing a native query for my project using JPA, but i don´t know how can I do a type of if and else
in a where clause, my ?0 can be 4 values: 10,20,30 and 40, when ?0 is 10, 20, 30 I should use CI.QTD <=
and when ?0 is 40, the condition should be >= . How can I do this?
Follow my code with one condition:
SELECT rownum AS id,
x.*
FROM (
SELECT ci.text,
ci.lenght
FROM ci_table CI
WHERE (?0 IS NULL OR ci.qtd <= ?0)
GROUP BY ci.text,
ci.lenght
ORDER BY ci.text) x ,
nativequery = true);
ADD THE QUERY AFTER THE ADJUSTMENT:
#Query(value =
"SELECT rownum as ID, X.* FROM (SELECT " +
" CI.PARAM1 " +
" CI.PARAM2, " +
" CI.PARAM3, " +
" CI.PARAM4, " +
" CI.PARAM5" +
" FROM " +
" CM_PARAMS CI " +
" WHERE " +
" (?1 is null or CI.PARAM6 = ?1) " +
" AND (?2 is null or CI.PARAM7 = ?2) " +
" AND (?3 is null or CI.PARAM8 = ?3) " +
" AND (?4 is null or CI.PARAM9 = ?4) " +
" AND (?5 is null or CI.PARAM10 = ?5) " +
" AND (?6 is null or CI.PARAM11 = ?6) " +
" AND (?7 is null or CI.PARAM12 = ?7) " +
" AND (?8 is null or CI.PARAM13 = ?8) " +
" AND (CASE WHEN ?9 >30 THEN CI.PARAM14 > 30 " +
" CASE WHEN ?9 <31 THEN CI.PARAM15 <= ?9 END) = 1 " +
" GROUP BY " +
" CI.PARAM1, " +
" CI.PARAM2, " +
" CI.PARAM3, " +
" CI.PARAM4, " +
" CI.PARAM5" +
" ORDER BY " +
" CI.PARAM1 ASC) X " , nativeQuery = true)
Try:
SELECT rownum AS id,
x.*
FROM (
SELECT ci.text,
ci.lenght
FROM ci_table CI
WHERE (CASE WHEN ?0 IN (10,20,30) THEN CI.QTD <= ?0
WHEN ?0 = 40 THEN CI.QTD > ?0 END) = 1
GROUP BY ci.text,
ci.lenght
ORDER BY ci.text) x ,
nativequery = true);

jpa query with case condition in criteria

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]