How to write SQL "not exists" in LINQ - sql

Here I sql query
Select emp.ID,emp.First_Name,w.week_num,w.week_start_dt,w.id,w.week_end_dt
from Employee emp,week_calender w
where not exists (select * from Timesheet where res_id=emp.id and week_cal_id=w.id)
and w.week_start_dt <= '08/06/2014'
order by w.ID
I have written linq query like
var employeesNotEnteredList = (from emps in reslandentity.EMPLOYEE
from week in reslandentity.WEEK_CALENDER
where reslandentity.TIMESHEET.Any(m=>m.RES_ID!=emps.ID && m.WEEK_CAL_ID!=week.ID)
&& week.WEEK_START_DT.Month == month
&& week.WEEK_START_DT.Year == year
&& emps.COMP_ID == Companyid
orderby week.ID
select new TimesheetModel
{
EMP_ID = emps.ID,
EMPLOYEE_NAME = emps.FIRST_NAME + " " + emps.LAST_NAME,
RES_TYPE = "EMPLOYEE",
SDate = week.WEEK_START_DT,
EDate = week.WEEK_END_DT,
EMP_STATUS = "NOT_ENTERED"
}).Distinct().ToList();
model.GetTimesheetNotEnteredDetails = employeesNotEnteredList;
But not getting exact results which is getting with sql query

Yes, Got it.
To get results
var employeesNotEnteredList = (from emps in reslandentity.EMPLOYEE
from week in reslandentity.WEEK_CALENDER
where !reslandentity.TIMESHEET.Any(m=>m.RES_ID==emps.ID && m.WEEK_CAL_ID==week.ID)
&& week.WEEK_START_DT.Month == month
&& week.WEEK_START_DT.Year == year
&& emps.COMP_ID == Companyid
orderby week.ID
select new TimesheetModel
{
EMP_ID = emps.ID,
EMPLOYEE_NAME = emps.FIRST_NAME + " " + emps.LAST_NAME,
RES_TYPE = "EMPLOYEE",
SDate = week.WEEK_START_DT,
EDate = week.WEEK_END_DT,
EMP_STATUS = "NOT_ENTERED"
}).Distinct().ToList();

Related

Go over a simple quote in a Where of a SQL query

I have a SQL query where I have to pass a string in my where, my string can have a simple quote in the name of the program and at the same time break the string and create an error in my request.
Yes I would just like to skip the code, but the actual logic has been done so that we are able to modify the code, so I can't just trust that.
Here is the query in my ASP.NET MVC 5 project:
IQueryable<ListeProgrammesCol> query = db.Database.SqlQuery<ListeProgrammesCol>(
"SELECT id AS offreID, nomProgramme AS nom, codeProgramme AS code, dateAjout, dateLastUpdate, gestionEnLigne " +
"FROM tbl_offreCol " +
"WHERE FK_etablissement = " + instId +" AND offreType = 3 AND archive = 0 AND codeProgramme = '" + code + "' AND nomProgramme = '" + progNom + "' " +
"ORDER BY nomProgramme").AsQueryable();
And here is the query if you want to text in SQL Server Management Studio:
SELECT
id AS offreID, nomProgramme AS nom, codeProgramme AS code,
dateAjout, dateLastUpdate, gestionEnLigne
FROM
tbl_offreCol
WHERE
FK_etablissement = 923000
AND offreType = 3
AND archive = 0
AND codeProgramme = '351.A0'
AND nomProgramme = 'RAC en Techniques d'éducation spécialisée'
ORDER BY
nomProgramme
This is the problem: d'éducation
//////UPDATE
I decided to use linq to make my request, so I no longer need to use quotes. Here is the query:
var query = (from oc in db.tbl_offreCol
where oc.FK_etablissement == instId
&& oc.offreType == 3
&& oc.archive == 0
&& oc.codeProgramme == code
&& oc.nomProgramme == progNom
select new ListeProgrammesCol
{
offreID = oc.id,
nom = oc.nomProgramme,
code = oc.codeProgramme,
dateAjout = oc.dateAjout,
dateLastUpdate = oc.dateLastUpdate,
gestionEnLigne = oc.gestionEnLigne
}).OrderBy(x => x.nom).AsQueryable();

Error when saving a date column to the underlying database using sqlitedatadapter

I would appreciate any help in finding why I get an error when saving back to a database. The error is: "Concurrency violation: the UpdateCommand affected 0 of the expected 1 records."
I have worked out that the error only occurs when my table has a date field which I fill from the underlying database use a sqlitedatadapter as follows:
Public connstring As String = "Data Source=c:\VS-2019\SaveTable\SaveTable\Data\TestDb.db"
Public conn As New SQLiteConnection
Public Sub FillMainTables()
conn.ConnectionString = connstring
conn.Open()
DTAllCustomers.Rows.Clear()
sql = "SELECT * FROM Customers"
AllCustomersAdapter = New SQLiteDataAdapter(sql, conn)
AllCustomersAdapter.Fill(DTAllCustomers)
End Sub
I then modify a few records in the datatable(DTAllCustomers) using this code
For i = 0 To DTAllCustomers.Rows.Count - 1
If DTAllCustomers.Rows(i).Item("sitecode") = "RESI" Then
DTAllCustomers.Rows(i).Item("Email") = "Changed"
End If
Next
I then try to save the modified table back to the underlying database with:
Dim cbAllCustomers As New SQLiteCommandBuilder(AllCustomersAdapter)
AllCustomersAdapter.UpdateCommand = cbAllCustomers.GetUpdateCommand
Try
AllCustomersAdapter.Update(DTAllCustomers)
Catch ex As Exception
MsgBox(ex.Message)
End Try
When I remove the DATETIME columns in DTAllCustomers the error disappears and the update completes correctly. Does SQLite change the date structure/value of the DateTime columns between filling the datatable and saving back to the datatable?
UpdateCommand.CommandText is:
UPDATE [main].[sqlite_default_schema].[Customers] SET [Email] = #param1
WHERE (([PrimaryKey] = #param2)
AND ([CustomerNumber] = #param3)
AND ((#param4 = 1 AND [Zone] IS NULL) OR ([Zone] = #param5))
AND ((#param6 = 1 AND [SiteCode] IS NULL) OR ([SiteCode] = #param7))
AND ((#param8 = 1 AND [FirstName] IS NULL) OR ([FirstName] = #param9))
AND ((#param10 = 1 AND [Surname] IS NULL) OR ([Surname] = #param11))
AND ((#param12 = 1 AND [Villa] IS NULL) OR ([Villa] = #param13))
AND ((#param14 = 1 AND [Village] IS NULL) OR ([Village] = #param15))
AND ((#param16 = 1 AND [Address] IS NULL) OR ([Address] = #param17))
AND ((#param18 = 1 AND [Suburb] IS NULL) OR ([Suburb] = #param19))
AND ((#param20 = 1 AND [PostCode] IS NULL) OR ([PostCode] = #param21))
AND ((#param22 = 1 AND [Phone] IS NULL) OR ([Phone] = #param23))
AND ((#param24 = 1 AND [Mobile1] IS NULL) OR ([Mobile1] = #param25))
AND ((#param26 = 1 AND [Mobile2] IS NULL) OR ([Mobile2] = #param27))
AND ((#param28 = 1 AND [Email] IS NULL) OR ([Email] = #param29))
AND ((#param30 = 1 AND [System] IS NULL) OR ([System] = #param31))
AND ((#param32 = 1 AND [Panels] IS NULL) OR ([Panels] = #param33))
AND ((#param34 = 1 AND [Isolator] IS NULL) OR ([Isolator] = #param35))
AND ((#param36 = 1 AND [Inverter] IS NULL) OR ([Inverter] = #param37))
AND ((#param38 = 1 AND [SolarHotWater] IS NULL) OR ([SolarHotWater] = #param39))
AND ((#param40 = 1 AND [Skylight] IS NULL) OR ([Skylight] = #param41))
AND ((#param42 = 1 AND [Rebate] IS NULL) OR ([Rebate] = #param43))
AND ((#param44 = 1 AND [Quote] IS NULL) OR ([Quote] = #param45))
AND ((#param46 = 1 AND [Notes] IS NULL) OR ([Notes] = #param47))
AND ((#param48 = 1 AND [LastCleaned] IS NULL) OR ([LastCleaned] = #param49))
AND ((#param50 = 1 AND [BookedInDate] IS NULL) OR ([BookedInDate] = #param51))
AND ((#param52 = 1 AND [BookedInOrder] IS NULL) OR ([BookedInOrder] = #param53))
AND ((#param54 = 1 AND [Frequency] IS NULL) OR ([Frequency] = #param55))
AND ((#param56 = 1 AND [NextCallDue] IS NULL) OR ([NextCallDue] = #param57))
AND ((#param58 = 1 AND [Status] IS NULL) OR ([Status] = #param59))
AND ((#param60 = 1 AND [Source] IS NULL) OR ([Source] = #param61)))
The parameter values and the date columns are in this format - #5/30/2018 12:00:00 AM#, however in the command text there is a #paramX = 1 for each column in the table and the paramX being passed has a value of 0.

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

SQL Server advanced sorting out

I am an asp.net web pages developer I am developing a website in which I need advanced sorting like www.olx.com which is a classifieds website but the problem is that I have more than 25 categories I am using SQL Server & have my tables broken into parts.
Now, as I have many categories so when i sort them for example if I search for samsung but at the same time I want to sort search data by price (high to low or low to high) & also at same time I want to filter data which has a description now I would need to make 100's of queries by using if's but is there a more convenient solution to this problem
Currently I am using this query:
sql = "SELECT * FROM users_table INNER JOIN response_table ON users_table.ID = response_table.ID LEFT OUTER JOIN miscellaneous_table ON users_table.ID = miscellaneous_table.ID LEFT OUTER JOIN response_table2 ON users_table.ID = response_table2.ID";
sql = sql + " where response_table.sub_category='" + incat + "'";
if (Request["search"] != "" && Request["search"] != null)
{
var search = Request["search"].Trim();
string[] querynew = search.Split(' ');
var searchquery = " and ";
foreach (string word in querynew)
{
searchquery += " users_table.adtitle LIKE '%" + word + "%' OR ";
}
sql = sql + searchquery.Remove(searchquery.Length - 4);
}
if (Request["min"] != "" && Request["min"] != null && Request["max"] != null && Request["max"] != "")
{
sql = sql + " and (CAST(response_table.price AS Float)) between " + Request["min"].Trim() + " AND " + Request["max"].Trim();
}
Thanks
You can use this short hand in the WHERE clause
Assuming your filter are #col1, #col2, #col3
SELECT ...
FROM ...
WHERE (#col1 = 0 OR col1 = #col1)
AND (#col2 = '' OR col2 = #col2)
AND (#col3 = 0 OR col3 = #col3)
So with the above where clause, if the user only supply filter for col2 then just pass 0 in for col1 & col2 and it will unfilter these.

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