How to convert following sql query to Linq,
Select F1, F2
From [Table]
Where Convert(Varchar(10), [OnDate], 103) = '12/08/2019'
The correct way to filter datetime values by date only is to use cast( ... as date) :
declare #myDate date='20190812'
Select F1, F2
From [Table]
Where cast([OnDate] as date)=#myDate
This avoids any parsing and localization errors and takes advantage of indexes that cover the OnDate column. Without it the server would have to scan the entire table to convert the dates into strings before comparing them.
This is due to the dynamic seek optimizations introduced at least as far back as SQL Server 2008 R2.
LINQ by itself doesn't query databases. It's a query language that gets translated by an ORM into actual SQL statements. Writing the equivalent of cast( ... as date) depends on the ORM.
In LINQ to SQL, calling DateTime.Date generates a cast( as date) :
var data = context.MyTable.Where(row=>row.OnDate.Date=someDate.Date);
or
var data = from row in contect.MyTable
where row.OnDate.Date=someDate.Date
select row;
EF doesn't recognize this and requires the DbFunctions.TruncateTime call :
var data = context.MyTable.Where(row=>DbFunctions.TruncateTime(row.OnDate)=someDate.Date);
EF Core once again recognizes DateTime.Date :
var data = context.MyTable.Where(row=>row.OnDate.Date=someDate.Date);
Related
I am using pyodbc with azure sql server
I had a query like this:
query = Update MyTable set MyDate = SYSDATETIME() where MyCol in ('val1', 'val2', 'val3')
cur = con.cursor()
cur.execute(query)
cur.commit()
I changed this query to use parameters:
query = Update MyTable set MyDate = SYSDATETIME() where MyCol in (?,?,?)
cur = con.cursor()
cur.execute(query, ['val1','val2', 'val3'])
cur.commit()
The parameterized query is much slower.
There are some similar questions I have seen on this site (SQL Server query takes longer with parameter than with constant string)
I am trying some of the suggestions and not seeing any improvements.
More specifically I have tried adding option(recompile) and option(recompile,use hint('DISABLE_PARAMETER_SNIFFING')) but not seeing any improvements.
In the example I am inserting three values but in the business scenario it's more like 200.
Thanks all.
Sql Query:
select Latitude,Langitude,Time from tblLatLang
where Time < GetDate()
and Time > (DateADD(mi, -50, GetDate()))
Sir I am new in Linq . I have the above SQL query and wants to convert it into Linq.The above query do fine work in SQL.
Here is the equivalent LINQ to Entities query:
var query =
from t in db.tblLatLang
where t.Time < DateTime.Now
&& t.Time > DbFunctions.AddMinutes(DateTime.Now, -50)
select new { t.Latitude, t.Langitude, t.Time };
As you can see, it's almost one to one translation. Just remember that LINQ select is after from :) Another detail specific for LINQ to Entities is that DateTime.AddMinutes method is not supported, so you should use DbFunctions.AddMinutes canonical function instead.
I'm trying to load incremental data from ODBC server to SQL server using common table expression.
When running the query in the Dbeabver application, is executed correctly:
with test as
(
SELECT userid,sum(goldbalance)
FROM Server.events_live
where eventTimestamp>=DATE '2016-01-01' + INTERVAL '-100 day'
group by userid
order by sum(goldbalance) desc)
)
select * from test
when running it from an sql command expression of the ODBC source, it fails due to wrong syntax. It looks as follow:
with test as
(
SELECT userid,sum(goldbalance)
FROM deltadna.events_live
where eventTimestamp>=DATE '"+#[User::datestring]+"' + INTERVAL '-100 day'
group by userid
order by sum(goldbalance) desc)
)
select * from test"
the datestring variable is getting the server date and convert it to string in the format yyyy-mm-dd. I'm usually use this method to pull data from ADO.NET and it works properly.
Is there any other way to pull incremental data from ODBC server using ssis variables?
With OLE DB
Try this code, it works for me with my own tables with SQL Server :
SELECT userid,sum(goldbalance) AS SUMGOLD
FROM deltadna.events_live
WHERE eventTimestamp >= DATEADD(DAY, -100,CONVERT(DATE,?))
GROUP BY userid
ORDER BY SUMGOLD desc
You have to click on Parameters in the OLEDB Source Editor to configure what you need. Use the '?' to represent a variable in your query.
If you query if too complicated, stored it in a stored procedure and call it like this:
EXEC shema.storedProcedureName ?
And map the '?' to your variable #user::DateString
With ODBC
The expressions are outside the data flow in Data Flow Properties.
Select the expression property and add your dynamic query.
And your expression will be
"SELECT userid,sum(goldbalance) AS SumGold
FROM deltadna.events_live
where eventTimestamp>=DATE "+#[User::datestring]+" +INTERVAL '-100 day'
group by userid
order by SumGold desc"
I have following query which takes almost 1 minute to execute.
public static Func<Entities, string, IQueryable<string>> compiledInvoiceQuery =
CompiledQuery.Compile((Entities ctx, string orderNumb) =>
(from order in ctx.SOP10100
where order.ORIGNUMB == orderNumb
select order.SOPNUMBE).Union(
from order in ctx.SOP30200
where order.ORIGNUMB == orderNumb
select order.SOPNUMBE)
);
It filters on basis of ORIGNUMB which is not my primary key, i can not even put any index on it. Do we have any other way to make it faster? I tested on sql server and found that only query
from order in ctx.SOP10100
where order.ORIGNUMB == orderNumb
select order.SOPNUMBE
or
select SOPNUMBE
from SOP10100
where ORIGNUMB = #orderNumb
is taking more than 55 seconds. Please suggest.
If it's taking 55 seconds on the server, then it's nowto to do with linq.
Why can't you have an index on it, because you need one....
Only other option is to rejig your logic to filter out records (using indexed columns), before you start searching for an ordernumber match.
One of the big problems with LINQ to SQL is that you have very little control over the SQL being generating.
Since you are running a union and not a join, it should be a pretty simple SQL. Something like this:
SELECT *
FROM SOP10100
WHERE ORIGNUMB = 'some number'
UNION
SELECT *
FROM SOP30200
WHERE ORIGNUMB = 'some number'
You can use SQL Server Profiler to see the SQL statements that are being run against the database to see if the SQL is like this or something more complicated. You can then run the SQL generated in SQL Server Management Stuido and turn on Include Client Statistics and Include Actual Execution Plan to see what exactly is causing the performance issue.
I'm new to Firebird, and I'm having particular difficulty translating this T-SQL to Firebird SQL. This code is stored outside of the database, not in a stored procedure.
DECLARE #NumTotal int
DECLARE #NumUsed int
SELECT #NumTotal = COUNT(*)
FROM "some_Table"
WHERE "CreatedOn"=#CreatedOn
SELECT #NumUsed = COUNT(*)
FROM "some_Table"
WHERE "CreatedOn"=#CreatedOn AND "UserID" IS NOT NULL
SELECT #NumUsed AS "NumUsed", #NumTotal AS "NumTotal"
I guess from the errors and my experimentation that I'm basically forced to put this into a stored procedure somehow. Is there a way I can do this while still keeping the code out of the database?
Your code can be simplified to a single query:
SELECT COUNT(*) AS numTotal,
(SELECT COUNT(*)
FROM YOUR_TABLE
WHERE userid IS NOT NULL
AND createdon = #createdon) AS numUsed
FROM YOUR_TABLE
WHERE createdon = #createdon
Using double quotes is ANSI for escaping unusual characters, none of which I see in the example.