Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to match same type of SQL Queries with different condition values,
For example :
SELECT * FROM Customer Where Age > 20 AND Age < 40
SELECT * FROM Customer Where Age > 30 AND Age < 50
Both of the above queries are the same except the values in the WHERE condition (20, 40, 30 and 50). I want to identify such queries. It should work with HAVING as well. It should work for any value type in the condition (int, varchar, date etc).
Basically I want to write a C# function to which I can pass 2 queries and it should return true if both queries are the same except the values in the exclusion condition.
Another Example :
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 50;
SELECT Employees.FirstName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY FirstName
HAVING COUNT(Orders.OrderID) > 50;
When I pass 1st and 2nd queries it should return true, but false for 2nd and 3rd.
I tried with Regular Expressions, but how to find where the parameter located? It can be anywhere.
Is it possible to do it with SqlScriptDom? How? I am using SqlScriptDom to get the table names from the SQL query, but how to get parameters?
Okay, I don't mean to pick on your language but I think it's kind of important here. The queries in your example don't have parameters. They have exclusion criteria in a WHERE clause. It sounds like what you're trying to do is compare the text of two queries for everything except the WHERE clause. ANSI SQL and T-SQL both follow the same convention that in a SELECT query the WHERE clause comes after the FROM clause and before any GROUP BY, HAVING or ORDER BY clause. So you could pull it out and compare it that way if you were going to just analyze the text of the code. One issue you might think about though is that SQL often provides subtly different ways of accomplishing the same thing. For example, if in your examples, you had <= and >= instead of < and > you could use the BETWEEN operator.
I think you probably could use the SqlScriptDom to do what you want but I'm not good enough with that to help really.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
When I execute following query , it is executed properly in SSMS but same query in code does not delete anything and 0 rows are affected from thousands of rows.
Code is excuted without any error , have tried Query parameters as well but not worked.
Logs is table and DateCreated is column of DateTime.
Sql Connection settings and other things are correct.
SSMS query execution below :
Can someone please correct this query for code ?
connection.Open();
SqlCommand cmd1 = new SqlCommand("delete TOP (100) from [Logs] WHERE DateCreated < GETDATE() - 30", connection);
var number_of_rows_deleted = cmd1.ExecuteNonQuery();
result = number_of_rows_deleted.ToString() + " records deleted";
When TOP is used with DELETE, the referenced rows are not arranged in any order and the ORDER BY clause can not be directly specified in this statement. If you need to use TOP to delete rows in a meaningful chronological order, you must use TOP together with an ORDER BY clause in a subselect statement
your sql script should be like this
DELETE from [Logs]
WHERE Id IN
(SELECT TOP(100) Id
FROM Logs
WHERE DATEDIFF(day, DateCreated, GETDATE()) < 30
Order By DateCreated )
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
How would I convert this SQL query to Linq?
Declare #Date Date
select #Date = Max (InsertedDate) from Rates
SELECT * FROM Rates where CAST(InsertedDate AS Date) =CAST(#Date AS Date) ORDER BY InsertedDate DESC
Your Sql Query appears to find all records on the last inserted date. Your Sql is approximately equivalent to:
var lastDate = db.Rates.Max(r => r.InsertedDate).Date;
var allRatesOnTheLastDate = db.Rates.Where(r => r.InsertedDate >= lastDate)
.OrderByDescending(r => r.InsertedDate);
This should be more performant than your Sql, given that you are casting the InsertedDate column which will prevent SARGability of any index on the column.
(Assuming an EF or Linq2Sql context called db with a Rates entity bound to it)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I've a complicated SQL query. I have to retrieve that from C#. What is the best method to retrieve complicated SQL queries? (Like QueryByAttribute, FetchXML, QueryExpression etc.)
Here is my code:
SELECT R.Name
FROM role R
WHERE R.roleid IN
(SELECT roleid
FROM systemuserroles SR
WHERE SR.systemuserid IN
(SELECT S.systemuserid
FROM systemuser S
WHERE S.new_departmentid3 =
(SELECT new_departmentid3
FROM systemuser S
WHERE S.systemuserid = '8B8825F9-6B27-E411-8BA9-000C29E0C100')))
Thanks for the replies.
If you are using an on-premise system I would use the Filtered Views and create a SQL query against them directly. This is by far the best performing option and is fully supported.
If this isn't an option because you are using CRM Online then FetchXML will give you the best performance available.
I'm going to disagree with Ben on a few issues:
The Filtered View contains security checks within them, and are designed to be able to run reports for users (they are not technically supported, but I have had only one breaking change over the course of 12 rollups, and it was realtively minor). The Non-Filtered Views are nearly identical, except that they don't contain all of the extra joins to ensure the user has access to query the information they are attempting to. So in this aspect, the Non-Filtered Views are going to give you the best possible performance, but I would recommend only using it when it makes a big performance difference, and only for reports. (Theoretically you could go directly to the Tables, but this is seems much more likely to be changed by Microsoft with any given Roll Up).
The best possible performance for large data requests available for online is not Fetch-Xml, but actually Odata since the payload is much smaller with O-Data than the Fetch Xml. However there are some technical limitations to using oData (You wouldn't be able to do your current query in one call due to it having too many joins, but you could do it in two).
P.S. I think this is an easier to read equivalent SQL statement:
SELECT R.Name
FROM role R
INNER JOIN systemuserroles SR ON R.roleId = SR.roleId
INNER JOIN SystemUser S ON SR.systemuserid = S.systemuserid
INNER JOIN systemuser S2 ON S.new_departmentid3 = S2.new_departmentid3
WHERE S2.systemuserid = '8B8825F9-6B27-E411-8BA9-000C29E0C100'
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I need to select a product for a user based on other data in the database.
If the data is filtered out on the database that will require less data to be send to the server.
User (Id)
Product (code)
Access (User_Id, code) // Matching users to object codes
Will this query execute on the database sending back the minimal amout of data?
var products = QueryOver.Of<Access>()
.Where(a => a.User_Id == User.Id())
.Select(Projections.Property<Acces>(a => a.Code));
var access = QueryOver.Of<Product>()
.WithSubquery.WhereProperty(h => h.Code)
.In(products)
.Future();
This is very reasonable way how to filter data. The result of your queries would look like one SELECT against the DB:
SELECT ...
FROM Product
WHERE Code IN (SELECT Code FROM Access WHERE UserId = #userId)
So, this will for sure be executed on the DB Server, less data will be transfered, and what's more, it also would allow you to do the correct paging (if needed) - this scenario is the way how to filter parent over its one-to-many relations (find Parents which child has...)
Maybe check these Join several queries to optimise QueryOver query, NHibernate QueryOver - Retrieve all, and mark the ones already "selected"
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Can someone please break this c# down in english? Is it possible to add a join in there somehow?
return db.Providers.Where(n => n.LastName.StartsWith(prefixText)).OrderBy(
n=>n.LastName).Select(n => n.LastName).Take(count).ToArray();
Thanks.
The SQL query is probably something like:
SELECT LastName FROM Providers
WHERE LastName LIKE 'PrefixText%'
ORDER BY LastName
LIMIT count; -- This may be TOP in MS SQL or ROWNUM in Oracle
Which means:
Give me all rows from the table Providers where the LastName column starts with PrefixText (whatever that variable contains). I want them sorted alphabetically by the LastName column, and I only want the first count rows (i.e., if count was equal to 50, you'd get up to 50 rows)
Sure, you can do a JOIN. You can refer to another table within your Where expression:
db.Providers.Where(n => n.ProviderGroup.ADgroup == 'Active Dir Group')
And the framework will automatically join in ADgroup for you, provided your model provides the necessary relationships between your tables.
Get x number of last name's of all Providers whose LastName starts with the text in the variable prefixText, in ascending alphabetical order.
This will return an array containing count last names, ordered in increasing alphabetical order, and starting with prefixText.
This is the corresponding SQL code:
select top #count LastName from Providers
where LastName like '+#prefixText+%'
order by LastName
Why do you need a join here?
Update:
Per the OP comment:
I need a join for limit the results of an Ajax auto extender...
You don't need a join for limiting the results in the Ajax Auto Extender, just use SQL's top clause or LINQ's Take method, just like you're doing right now:
db.Providers.Where(n => n.LastName.StartsWith(prefixText)).OrderBy(
n=>n.LastName).Select(n => n.LastName).Take(count).ToArray();