how to optimized sql query for speed up performance - sql

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!!

Related

how to get all query result summary to grid view with asp.net 4.0

I have one page as remove duplicates and it's gets all duplicates values from 4 tables. now for grid view bind I use same preference for associated column name. but it'd gets only first query result.
here is my sql management studio result:
and here is my code :
string str = "";
DataTable dt = new DataTable();
str += "(SELECT ";
str += "s.Id, s.EmailAddress As ColumnValue,";
str += "(SELECT Name FROM tbl_User_master ";
str += "WHERE Id = s.user_id) AS CreatedBy,";
str += "d.Count ";
str += "FROM ";
str += "(SELECT EmailAddress, COUNT(*) as Count ";
str += "FROM tbl_Subscribers ";
str += "WHERE user_id = '1' ";
str += "GROUP BY EmailAddress ";
str += "HAVING COUNT(*) > 1) AS d ";
str += "INNER JOIN ";
str += "tbl_Subscribers s ON s.EmailAddress = d.EmailAddress)";
str += "(SELECT ";
str += "f.Id,f.EmailAddress As ColumnValue,";
str += "(SELECT Name FROM tbl_User_master WHERE Id = f.user_id) AS CreatedBy,";
str += "d.Count ";
str += "FROM ";
str += "(SELECT EmailAddress, COUNT(*) AS Count ";
str += "FROM tbl_From_master ";
str += "WHERE user_id = '1' ";
str += "GROUP BY EmailAddress ";
str += "HAVING COUNT(*) > 1) AS d ";
str += "INNER JOIN ";
str += "tbl_From_master f ON f.EmailAddress = d.EmailAddress)";
str += "(SELECT ";
str += "c.Id,c.CategoryName As ColumnValue,(SELECT Name FROM tbl_User_master WHERE Id = c.user_id) As CreatedBy, d.Count ";
str += "FROM (";
str += "SELECT CategoryName, COUNT(*) as Count ";
str += "FROM tbl_Categories WHERE user_id='1' ";
str += "GROUP BY CategoryName ";
str += "HAVING COUNT(*) > 1";
str += ") AS d ";
str += "INNER JOIN tbl_Categories c ON c.CategoryName = d.CategoryName)";
str += "(SELECT ";
str += "t.Id,t.CategoryName As ColumnValue,(SELECT Name FROM tbl_User_master WHERE Id = t.user_id) As CreatedBy, d.Count ";
str += "FROM (";
str += "SELECT CategoryName, COUNT(*) as Count ";
str += "FROM tbl_Template_Categories WHERE user_id='1' ";
str += "GROUP BY CategoryName ";
str += "HAVING COUNT(*) > 1";
str += ") AS d ";
str += "INNER JOIN tbl_Template_Categories t ON t.CategoryName = d.CategoryName)";
str += "(SELECT ";
str += "t.Id,t.TemplateName As ColumnValue,(SELECT Name FROM tbl_User_master WHERE Id = t.user_id) As CreatedBy,d.Count ";
str += "FROM (";
str += "SELECT TemplateName, COUNT(*) as Count ";
str += "FROM tbl_Template_master WHERE user_id='1' ";
str += "GROUP BY TemplateName ";
str += "HAVING COUNT(*) > 1";
str += ") AS d";
str += " INNER JOIN tbl_Template_master t ON t.TemplateName = d.TemplateName)";
dt = obj.Get_Data_Table_From_Str(str);
egrd.DataSource = dt;
egrd.DataBind();
ViewState["data"] = dt;
but still returns only first query result :
here I include my grid view markup:
<asp:GridView ID="egrd" runat="server" AutoGenerateColumns="true" CssClass="table table-striped table-bordered table-hover"
Width="100%" PageSize="9999999" HeaderStyle-CssClass="theme-font" OnPreRender="egrd_PreRender">
<EmptyDataTemplate>
<asp:Label ID="lblEmptySearch" runat="server" Font-Bold="true" ForeColor="Red">No Data Found To Display . . .</asp:Label>
</EmptyDataTemplate>
<Columns>
</Columns>
<HeaderStyle CssClass="theme-font"></HeaderStyle>
<RowStyle Wrap="False" />
</asp:GridView>
how I achieve this task please help me...
-----------------------Updated---------------------------
ok I done with it :
if (groupByTable == 0)
{
str += "(SELECT ";
str += "s.Id, s.EmailAddress As ColumnValue,";
str += "(SELECT Name FROM tbl_User_master ";
str += "WHERE Id = s.user_id) AS CreatedBy,";
str += "s.SubscriptionDateTime As CreatedDate,d.Count ";
str += "FROM ";
str += "(SELECT EmailAddress, COUNT(*) as Count ";
str += "FROM tbl_Subscribers ";
str += "WHERE user_id = '" + int.Parse(CommonLogic.GetSessionValue("user_id").ToString()) + "' ";
str += "GROUP BY EmailAddress ";
str += "HAVING COUNT(*) > 1) AS d ";
str += "INNER JOIN ";
str += "tbl_Subscribers s ON s.EmailAddress = d.EmailAddress)";
str += " UNION ALL ";
str += "(SELECT ";
str += "f.Id,f.EmailAddress As ColumnValue,";
str += "(SELECT Name FROM tbl_User_master WHERE Id = f.user_id) AS CreatedBy,";
str += "f.CreatedDate As CreatedDate,d.Count ";
str += "FROM ";
str += "(SELECT EmailAddress, COUNT(*) AS Count ";
str += "FROM tbl_From_master ";
str += "WHERE user_id = '" + int.Parse(CommonLogic.GetSessionValue("user_id").ToString()) + "' ";
str += "GROUP BY EmailAddress ";
str += "HAVING COUNT(*) > 1) AS d ";
str += "INNER JOIN ";
str += "tbl_From_master f ON f.EmailAddress = d.EmailAddress)";
str += " UNION ALL ";
str += "(SELECT ";
str += "c.Id,c.CategoryName As ColumnValue,(SELECT Name FROM tbl_User_master WHERE Id = c.user_id) As CreatedBy,NULL As CreatedDate,d.Count ";
str += "FROM (";
str += "SELECT CategoryName, COUNT(*) as Count ";
str += "FROM tbl_Categories WHERE user_id='" + int.Parse(CommonLogic.GetSessionValue("user_id").ToString()) + "' ";
str += "GROUP BY CategoryName ";
str += "HAVING COUNT(*) > 1";
str += ") AS d ";
str += "INNER JOIN tbl_Categories c ON c.CategoryName = d.CategoryName)";
str += " UNION ALL ";
str += "(SELECT ";
str += "t.Id,t.CategoryName As ColumnValue,(SELECT Name FROM tbl_User_master WHERE Id = t.user_id) As CreatedBy,NULL As CreatedDate,d.Count ";
str += "FROM (";
str += "SELECT CategoryName, COUNT(*) as Count ";
str += "FROM tbl_Template_Categories WHERE user_id='" + int.Parse(CommonLogic.GetSessionValue("user_id").ToString()) + "' ";
str += "GROUP BY CategoryName ";
str += "HAVING COUNT(*) > 1";
str += ") AS d ";
str += "INNER JOIN tbl_Template_Categories t ON t.CategoryName = d.CategoryName)";
str += " UNION ALL ";
str += "(SELECT ";
str += "t.Id,t.TemplateName As ColumnValue,(SELECT Name FROM tbl_User_master WHERE Id = t.user_id) As CreatedBy,t.Created_date As CreatedDate,d.Count ";
str += "FROM (";
str += "SELECT TemplateName, COUNT(*) as Count ";
str += "FROM tbl_Template_master WHERE user_id='" + int.Parse(CommonLogic.GetSessionValue("user_id").ToString()) + "' ";
str += "GROUP BY TemplateName ";
str += "HAVING COUNT(*) > 1";
str += ") AS d";
str += " INNER JOIN tbl_Template_master t ON t.TemplateName = d.TemplateName)";
}

how to know rows retrived form multiple tables to grid view with which table name

I have query to gets duplicates records and union all them for binds to grid view with success. now I just want to know at deleting time selected records are being form which table. Is that possible with multiple tables rows.
str += "(SELECT ";
str += "s.Id, s.EmailAddress As ColumnValue,";
str += "(SELECT Name FROM tbl_User_master ";
str += "WHERE Id = s.user_id) AS CreatedBy,";
str += "s.SubscriptionDateTime As CreatedDate,d.Count ";
str += "FROM ";
str += "(SELECT EmailAddress, COUNT(*) as Count ";
str += "FROM tbl_Subscribers ";
str += "WHERE user_id = '" + int.Parse(CommonLogic.GetSessionValue("user_id").ToString()) + "' ";
str += "GROUP BY EmailAddress ";
str += "HAVING COUNT(*) > 1) AS d ";
str += "INNER JOIN ";
str += "tbl_Subscribers s ON s.EmailAddress = d.EmailAddress)";
str += " UNION ALL ";
str += "(SELECT ";
str += "f.Id,f.EmailAddress As ColumnValue,";
str += "(SELECT Name FROM tbl_User_master WHERE Id = f.user_id) AS CreatedBy,";
str += "f.CreatedDate As CreatedDate,d.Count ";
str += "FROM ";
str += "(SELECT EmailAddress, COUNT(*) AS Count ";
str += "FROM tbl_From_master ";
str += "WHERE user_id = '" + int.Parse(CommonLogic.GetSessionValue("user_id").ToString()) + "' ";
str += "GROUP BY EmailAddress ";
str += "HAVING COUNT(*) > 1) AS d ";
str += "INNER JOIN ";
str += "tbl_From_master f ON f.EmailAddress = d.EmailAddress)";
str += " UNION ALL ";
str += "(SELECT ";
str += "c.Id,c.CategoryName As ColumnValue,(SELECT Name FROM tbl_User_master WHERE Id = c.user_id) As CreatedBy,NULL As CreatedDate,d.Count ";
str += "FROM (";
str += "SELECT CategoryName, COUNT(*) as Count ";
str += "FROM tbl_Categories WHERE user_id='" + int.Parse(CommonLogic.GetSessionValue("user_id").ToString()) + "' ";
str += "GROUP BY CategoryName ";
str += "HAVING COUNT(*) > 1";
str += ") AS d ";
str += "INNER JOIN tbl_Categories c ON c.CategoryName = d.CategoryName)";
str += " UNION ALL ";
str += "(SELECT ";
str += "t.Id,t.CategoryName As ColumnValue,(SELECT Name FROM tbl_User_master WHERE Id = t.user_id) As CreatedBy,NULL As CreatedDate,d.Count ";
str += "FROM (";
str += "SELECT CategoryName, COUNT(*) as Count ";
str += "FROM tbl_Template_Categories WHERE user_id='" + int.Parse(CommonLogic.GetSessionValue("user_id").ToString()) + "' ";
str += "GROUP BY CategoryName ";
str += "HAVING COUNT(*) > 1";
str += ") AS d ";
str += "INNER JOIN tbl_Template_Categories t ON t.CategoryName = d.CategoryName)";
str += " UNION ALL ";
str += "(SELECT ";
str += "t.Id,t.TemplateName As ColumnValue,(SELECT Name FROM tbl_User_master WHERE Id = t.user_id) As CreatedBy,t.Created_date As CreatedDate,d.Count ";
str += "FROM (";
str += "SELECT TemplateName, COUNT(*) as Count ";
str += "FROM tbl_Template_master WHERE user_id='" + int.Parse(CommonLogic.GetSessionValue("user_id").ToString()) + "' ";
str += "GROUP BY TemplateName ";
str += "HAVING COUNT(*) > 1";
str += ") AS d";
str += " INNER JOIN tbl_Template_master t ON t.TemplateName = d.TemplateName)";
how ever grid view binds up every rows with unique id but how ever know given id from which table.

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

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

regularexpression for this text sql statement or a program?

Heres specifically the sql text in a file.
select substr(to_char(ctl.tody_run_dt,'YYYYMMDD'),1,8) tody_yyyymmdd,
substr(to_char(cdr.nxt_proc_dt,'YYYYMMDD'),1,8) nxt_proc_yyyymmdd,
add_months(ctl.tody_run_dt - cdr.past_accru_dys,
- ct.nbr_cycl_for_adj) beg_proc_dt,
from tbl_crd )
and prv.calendar_run_dt =
( select max(calendar_run_dt)
from run_tbl1 prv2
From this i wish to extract all the tables,
This seems pretty complicated to be done through a regexp? Is there a way? Or should i write a program? I just cant come up with an algorithm.
You might be able to do something like a linear search like this. It relaxed for your example
and just targets the from keyword, excludes other keywords.
The table data is captured in group 1. It has to be split appart upon each
match through the find loop.
# from\s+((?!(?:select|from|where|and)\b)\w+(?:[,\s]+(?!(?:select|from|where|and)\b)\w+)*)
from
\s+
( # (1 start), Contains all the table info
(?! # exclude keywords
(?:
select
| from
| where
| and
)
\b
)
\w+
(?:
[,\s]+
(?! # exclude keywords
(?:
select
| from
| where
| and
)
\b
)
\w+
)*
) # (1 end)
Perl test case
$/ = undef;
$str = <DATA>;
while ( $str =~ /from\s+((?!(?:select|from|where|and)\b)\w+(?:[,\s]+(?!(?:select|from|where|and)\b)\w+)*)/g )
{
print "\n'$1'";
}
__DATA__
select substr(to_char(ctl.tody_run_dt,'YYYYMMDD'),1,8) tody_yyyymmdd,
substr(to_char(cdr.nxt_proc_dt,'YYYYMMDD'),1,8) nxt_proc_yyyymmdd,
add_months(ctl.tody_run_dt - cdr.past_accru_dys,
- ct.nbr_cycl_for_adj) beg_proc_dt,
(ctl.tody_run_dt + cdr.futr_accru_dys) end_proc_dt,
ctl.tody_end_proc_dt,
ctl.prv_end_proc_dt,
cdr.fst_proc_dy,
cdr.lst_proc_dy,
cdr.accru_nbr_of_dys,
cdr.dy_of_wk,
from run_tbl1 cdr, runtbl
run_tbl1 prv,
run_tbl_cntl ctl,
tbl_crd ct
where cdr.calendar_run_dt = ctl.tody_run_dt
and ct.nbr_cycl_for_adj =
( select max(nbr_cycl_for_adj)
from tbl_crd )
and prv.calendar_run_dt =
( select max(calendar_run_dt)
from run_tbl1 prv2
where prv2.calendar_run_dt < ctl.tody_run_dt
and prv2.accru_nbr_of_dys = 1 )
and rownum = 1
Output >>
'run_tbl1 cdr, runtbl
run_tbl1 prv,
run_tbl_cntl ctl,
tbl_crd ct'
'tbl_crd'
'run_tbl1 prv2'
First I had to correct some syntax errors within your SQL.
... cdr.dy_of_wk, <<<< the comma is wrong
from run_tbl1 cdr ...
Here the proove of concept using JSQLParser V0.8.9 (https://github.com/JSQLParser/JSqlParser) to extract tablenames.
public static void main(String[] args) throws JSQLParserException {
TablesNamesFinder tfinder = new TablesNamesFinder();
String sql = "select substr(to_char(ctl.tody_run_dt,'YYYYMMDD'),1,8) tody_yyyymmdd, "
+ " substr(to_char(cdr.nxt_proc_dt,'YYYYMMDD'),1,8) nxt_proc_yyyymmdd, "
+ " add_months(ctl.tody_run_dt - cdr.past_accru_dys, "
+ " - ct.nbr_cycl_for_adj) beg_proc_dt, "
+ " (ctl.tody_run_dt + cdr.futr_accru_dys) end_proc_dt, "
+ " ctl.tody_end_proc_dt, "
+ " ctl.prv_end_proc_dt, "
+ " cdr.fst_proc_dy, "
+ " cdr.lst_proc_dy, "
+ " cdr.accru_nbr_of_dys, "
+ " cdr.dy_of_wk "
+ " from run_tbl1 cdr, runtbl, "
+ " run_tbl1 prv, "
+ " run_tbl_cntl ctl, "
+ " tbl_crd ct "
+ " where cdr.calendar_run_dt = ctl.tody_run_dt "
+ " and ct.nbr_cycl_for_adj = "
+ " ( select max(nbr_cycl_for_adj) "
+ " from tbl_crd ) "
+ " and prv.calendar_run_dt = "
+ " ( select max(calendar_run_dt) "
+ " from run_tbl1 prv2 "
+ " where prv2.calendar_run_dt < ctl.tody_run_dt "
+ " and prv2.accru_nbr_of_dys = 1 ) "
+ " and rownum = 1 ";
//parse SQL statement
Select select = (Select) CCJSqlParserUtil.parse(sql);
//extract table names
List<String> tableList = tfinder.getTableList(select);
System.out.println(tableList);
}
and it outputs
[run_tbl1, runtbl, run_tbl_cntl, tbl_crd]