I am working on a project that require me to join four tables. I have written this code but it's taking forever to finish. Please help. Ohhh I have about 121 000 entries in the Db
PortfolioCollectionDataContext context = null;
context = DataContext;
var Logins = from bkg in context.EnquiryBookings
where bkg.Paid == true
from log in context.Logins
where log.LoginID == bkg.LoginID
from enq in context.Enquiries
where enq.EnquiryID == bkg.EnquiryID
from estb in context.Establishments
where enq.EstablishmentID == estb.EstablishmentID
select new
{
log.LoginID,
log.FirstName,
log.LastName,
log.CountryOfResidence,
log.EmailAddress,
log.TelephoneNumber,
bkg.TotalPrice,
estb.CompanyName
};
string str = "";
foreach (var user in Logins)
{
str += ("[Name: " + user.LastName + " " + user.FirstName + " - Country: " + user.CountryOfResidence + " - Phone: " + user.TelephoneNumber + " - Email: " + user.EmailAddress + " - Booked From: " + user.CompanyName + " - Spent: " + user.TotalPrice.ToString() + "]");
}
return str;
Use following query on LINQ
PortfolioCollectionDataContext context = null;
context = DataContext;
var Logins = from bkg in context.EnquiryBookings
join log in context.Logins
on log.LoginID equals bkg.LoginID
&& bkg.Paid == true
join enq in context.Enquiries
on enq.EnquiryID equals bkg.EnquiryID
join estb in context.Establishments
on enq.EstablishmentID == estb.EstablishmentID
select new
{
str = "[Name: " + log.LastName + " " + log.FirstName + " - Country: " + log.CountryOfResidence + " - Phone: "
+ log.TelephoneNumber + " - Email: " + log.EmailAddress + " - Booked From: "
+ estb.CompanyName + " - Spent: " + bkg.TotalPrice.ToString() + "]"
};
string output = string.Join(", ", Logins.ToList());
return output;
Check your query by taking cursor on Logins and paste that query here. Then check an estimated execution plan of your query and paste here.
If using SQL Server, to get execution plan of your query using Sql server management studio, click on an icon highlighted in an image below.
Related
Right now I am using the following code to generate the WHERE clause in my query. I have a parameter for the search column (searchColumn) plus another parameter from a checked listbox that I use.
If no item is checked there is no WHERE clause at all.
Is it possible to put this into a parameterized query? For the second part there's most likely a way like searchColumn NOT IN ( ... ) where ... ist the data from an array. Though I am not sure how to handle the case when there's nothing checked at all.
Any thoughts or links on this?
strWhereClause = "";
foreach (object objSelected in clbxFilter.CheckedItems)
{
string strSearch = clbxFilter.GetItemText(objSelected);
if (strWhereClause.Length == 0)
{
strWhereClause += "WHERE (" + searchColumn + " = '" + strSearch + "' "
+ "OR " + searchColumn + " = '" + strSearch + "') ";
}
else
{
strWhereClause += "OR (" searchColumn " = '" + strSearch + "' "
+ "OR " + searchColumn + " = '" + strSearch + "') ";
}
}
It sounds like you're just trying to dynamically build a parameterized query string using C#. You're halfway there with your code - my example below builds up a dictionary with paramter names and parameter values, which you can then use to create SqlParamters. One thing I'm not 100% sure about is where searchColumn is coming from - is this generated from user input? That could be dangerous, and parameterizing that would require using some dynamic SQL and probably some validation on your part.
strWhereClause = "";
Dictionary<string, string> sqlParams = new Dictionary<string, string>();
int i = 1;
string paramName= "#p" + i.ToString(); // first iteration: "#p1"
foreach (object objSelected in clbxFilter.CheckedItems)
{
string strSearch = clbxFilter.GetItemText(objSelected);
if (strWhereClause.Length == 0)
{
strWhereClause += "WHERE (thisyear." + strKB + " = #p1 OR " + searchColumn + " = #p1) ";
sqlParams.Add(paramName, strSearch);
i = 2;
}
else
{
paramName = "#p" + i.ToString(); // "#p2", "#p3", etc.
strWhereClause += "OR (" searchColumn " = " + paramName + " "OR " + searchColumn + " = " + paramName + ") ";
sqlParams.Add(paramName, strSearch);
i++;
}
}
Then, when parameterizing your query, just loop through your dictionary.
if (sqlParams.Count != 0 && strWhereclause.Length != 0)
{
foreach(KeyValuePair<string, string> kvp in sqlParams)
{
command.Parameters.Add(new SqlParamter(kvp.Name, SqlDbType.VarChar) { Value = kvp.Value; });
}
}
For reference only:
string strWhereClause;
string searchColumn;
string strKB;
SqlCommand cmd = new SqlCommand();
private void button1_Click(object sender, EventArgs e)
{
strWhereClause = "";
int ParmCount = 0;
foreach (object objSelected in clbxFilter.CheckedItems)
{
string strSearch = clbxFilter.GetItemText(objSelected);
ParmCount += 1;
string strParamName = "#Param" + ParmCount.ToString(); //Param1→ParamN
cmd.Parameters.Add(strParamName, SqlDbType.NVarChar);
cmd.Parameters[strParamName].Value = strSearch;
if (strWhereClause.Length == 0)
{
strWhereClause += "WHERE (thisyear." + strKB + " = " + strParamName + " "
+ "OR " + searchColumn + " = " + strParamName + ") ";
}
else
{
strWhereClause += "OR (thisyear." + strKB + " = " + strParamName + " "
+ "OR " + searchColumn + " = " + strParamName + ") ";
}
}
}
The original query I have is somewhat complex, but what I'm trying to do is obtain the entity AlertCondition plus some additional fields.
+ " SELECT new org.rhq.core.domain.alert.composite.AlertConditionEventCategoryComposite " //
+ " ( " //
+ " ac, " //
+ " res.id " //
+ " ) " //
+ " FROM AlertCondition AS ac FETCH ALL PROPERTIES " //
+ " JOIN ac.alertDefinition ad " //
+ " JOIN ad.resource res " //
+ " WHERE " + AlertCondition.RECOVERY_CONDITIONAL_EXPRESSION //
+ " AND ( res.agent.id = :agentId OR :agentId IS NULL ) " //
+ " AND ad.enabled = TRUE " //
+ " AND ad.deleted = FALSE " //
+ " AND ac.category = 'EVENT' " //
+ "ORDER BY ac.id"), //
The problem is Hibernate only selects the ID of AlertCondition, so when accessing this object, this ends up requiring N+1 selects whereas I would like to do only 1.
The select is only fetching the ID column, according to debug:
select alertcondi0_.ID as col_0_0_, alertdefin1_.ID as col_1_0_, resource2_.ID as col_2_0_
What I'm trying to get back are all the fields of *AlertCondition.
I can't find any way to do this under Hibernate. JOIN FETCH doesn't really work here either.
The alternative is to select every column of the table, which I'd like to avoid.
Facing the same issue.
I don't know how to let hibernate fetch ac.* neither.
But I found a workaround.
#Query("select ac, xxx, zzz")
List<Object[]> fetchRecords()
//
Constructor<?> constructor = AlertConditionEventCategoryComposite.class.getDeclaredConstructors()[0];
List<AlertConditionEventCategoryComposite> composites = fetchRecords.stream().map(constructor::newInstance).collect(Collectors.toList());
You can tell hibernate to fetch an ad with:
JOIN FETCH ac.alertDefinition ad
I know similar questions has been before but I just couldn't quite understand them, still very new to SQL and wanting to get the solution as well as understanding why it wouldn't work originally.
sql = "UPDATE e " +
"SET " +
"e.Operator = '" + emp.Operator + "', " +
"e.LoginName = '" + emp.Login + "', " +
"e.Active = " + (emp.Active == true ? 1 : 0) + "," +
"e.Position = '" + emp.Position + "', " +
"p.Admin = " + (emp.Permission.Admin == true ? 1 : 0) + "," +
"p.Manager = " + (emp.Permission.Manager == true ? 1 : 0) + "," +
"p.Overtime = " + (emp.Permission.Overtime == true ? 1 : 0) + "," +
"p.TimeInLieu = " + emp.Permission.TimeInLieu + " " +
"FROM Employee e INNER JOIN Permissions p " +
"ON e.PermissionID = p.PermissionID AND e.Operator = '" + employee + "'";
when trying to execute the command I get this error.
The multi-part identifier "p.Admin" could not be bound.
Any help would be greatly received.
I Work on C# Project (WinForm)
I Install Sql Server 2008 Express On Client PC.
in Start Of My Program Must Create a Database. So I Use This Code For Create a Database:
string sqlCreateDBQuery;
SqlConnection tmpConn = new SqlConnection(#"SERVER =.\SQLEXPRESS; Trusted_Connection = yes;DATABASE = master;");
sqlCreateDBQuery = " CREATE DATABASE "
+ DatabaseName
+ " ON PRIMARY "
+ " (NAME = " + DatabaseName + ", "
+ " FILENAME = '" + #"C:" + #"\" + DatabaseName + ".mdf" + "', "
+ " SIZE = 3MB,"
+ " FILEGROWTH = " + "10%" + ") "
+ " LOG ON (NAME =" + "MyDatabase_Log" + ", "
+ " FILENAME = '" + #"C:" + #"\" + DatabaseName + "_log.ldf" + "', "
+ " SIZE = 1MB, "
+ " FILEGROWTH = " + "10%" + ") ";
sqlCreateDBQuery = Coomand;
SqlCommand myCommand = new SqlCommand(sqlCreateDBQuery, tmpConn);
try
{
tmpConn.Open();
MessageBox.Show(sqlCreateDBQuery);
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
tmpConn.Close();
}
return;
But When My Program Run I See Following Error
What is My Problem?
It looks from the error message that you don't have permissions to create your mdf file on the root. Truth be told, you should not have put it there anyway, as that is much too exposed. Put it in your application's folder, or somewhere obscure where it won't be accidentally deleted.
I also think that you should be running this as a install script for the initial setup, rather than in your code. I am a big proponent of keeping sql out of code as much as possible, but to each his own. You say you set up the SQL Server DB, you should use the tools at your disposal to make this easy for you. I had a book from Wrox that served me well, here is the link: http://www.wrox.com/WileyCDA/WroxTitle/Wrox-s-SQL-Server-2005-Express-Edition-Starter-Kit.productCd-0764589237.html -Amazon has it for $2 - http://www.amazon.com/Server-Express-Edition-Starter-Programmer/dp/B006TQYC8U/ref=sr_1_1?ie=UTF8&qid=1342019983&sr=8-1&keywords=Wrox%27s+SQL+Server+2005+Express+Edition+Starter+Kit
Also:
http://msdn.microsoft.com/en-us/library/bb264562(v=sql.90).aspx
In the following code, i want to add "IN" +Village+. Where to add this condition in the code. Variable village takes value from a drop down list based on that filter should occur.please help me.Village name is a column in my fusion table.
i.e select 'geometry',villageName from table where querypass > textvalue IN villagename='madurai'
function querymape()
{
/*variable holds the value*/
var village =document.getElementById('village').value.replace(/'/g, "\\'");
var operatore=document.getElementById('operatorstringe').value.replace(/'/g, "\\'");
var textvaluee=document.getElementById("text-valuee").value.replace(/'/g, "\\'");
var querypasse=document.getElementById('query-passe').value.replace(/'/g, "\\'");
{
layer.setQuery("SELECT 'geometry'," + querypasse + " FROM " + tableid + " WHERE " + querypasse + " " + operatore + " '" + textvaluee + "'"+"AND 'VillageName=+village+'");
}
}
/*This is my new code.But its not working.Please help me*/
function querymap()
{
//var villagename='';
var operator=document.getElementById('operatorstring').value.replace(/'/g, "\\'");
var textvalue=document.getElementById("text-value").value.replace(/'/g, "\\'");
var querypass=document.getElementById('query-pass').value.replace(/'/g, "\\'");
var searchStringe = document.getElementById('Search-stringe').value.replace(/'/g, "\\'");
{
layer.setQuery("SELECT 'geometry'," + querypass + " FROM " + tableid + " WHERE " + querypass + " " + operator + " '" + textvalue + "'"+"AND 'VillageName'="+ searchStringe+"");
}
}
Multiple conditions can be combined using the keyword "and"?
You twisted the IN syntax around, it is used when you want to match several values, if you only want to compare to a single value use "=" instead
Applied to your query (with IN syntax):
select 'geometry',villageName from table where querypass > textvalue and villagename IN ('madurai','another village')
With = syntax:
select 'geometry',villageName from table where querypass > textvalue and villagename = 'madurai'