LINQ adding format to date column in where clause - linq-to-sql

select *
from qmsCallAudit
where CAST(FLOOR(CAST(callauditdt AS float)) AS DATETIME)
between '2015-07-16 00:00:00' and '2015-07-16 00:00:00'
above query return records in sql query
from linq its not not working, below is application code
var query = (
from qd in db.qmsCallAuditDetails
from qm in db.qmsCallAudits
where qm.callaudit_id == qd.callaudit_id &&
qm.active == true
&& qm.process_id == processid
&& fdt >= qm.callauditdt
&& tdt <= qm.callauditdt
select qd
).AsQueryable();
string semp = frm["employee_id"];
if (semp.Length > 0)
{
int empid = Convert.ToInt32(frm["employee_id"]);
query = query.Where(q => q.qmsCallAudit.employee_id==empid);
}
below sql profile code for above linq query
exec sp_executesql N'SELECT
[Extent1].[callauditdetail_id] AS [callauditdetail_id],
[Extent1].[callaudit_id] AS [callaudit_id],
[Extent1].[subparameter_id] AS [subparameter_id],
[Extent1].[subparameterdisp_id] AS [subparameterdisp_id],
[Extent1].[score] AS [score],
[Extent1].[weightage] AS [weightage],
[Extent1].[fatal] AS [fatal],
[Extent1].[add_to_weightage] AS [add_to_weightage],
[Extent1].[auditstatus] AS [auditstatus],
[Extent1].[auditscore] AS [auditscore],
[Extent1].[auditweightage] AS [auditweightage],
[Extent1].[auditremark] AS [auditremark],
[Extent1].[createdon] AS [createdon],
[Extent1].[createdby] AS [createdby],
[Extent1].[modifiedon] AS [modifiedon],
[Extent1].[modifiedby] AS [modifiedby],
[Extent1].[active] AS [active]
FROM [dbo].[qmsCallAuditDetail] AS [Extent1]
INNER JOIN [dbo].[qmsCallAudit] AS [Extent2] ON [Extent2].[callaudit_id] = [Extent1].[callaudit_id]
WHERE (1 = [Extent2].[active]) AND ([Extent2].[process_id] = #p__linq__0) AND (#p__linq__1 >= [Extent2].CAST(FLOOR(CAST(callauditdt AS float)))[callauditdt]) AND (#p__linq__2 <= [Extent2].[callauditdt])',N'#p__linq__0 int,#p__linq__1 datetime2(7),#p__linq__2 datetime2(7)',#p__linq__0=2,#p__linq__1='2015-07-16 00:00:00',#p__linq__2='2015-07-16 00:00:00'

Whats your error? Are your ftd and tdt already dateTime objects?

Related

LINQ MY SQL QUERY "BIGINT UNSIGNED value is out of range in"

I've got a strange situation.
I've got a column (smallint) that has a single value of 6
I run using a linq to retrieve records that are Validity_months old.
var query = db.table_1
.AsNoTracking()
.Include(b => b.table_2)
.ThenInclude(t => t.table_3)
.Where(e => e.Date <= DateTime.UtcNow.AddMonths(e.table_2.ValidityMonths))
.Where(e => e.Date >= DateTime.UtcNow.AddMonths(e.table_2.ValidityMonths*-1)));
This throws an MySQL Error
Error Code: 1690. BIGINT UNSIGNED value is out of range in '(database.s0.validity_months * (-(1)))'
The query above translates into SQL Query
SELECT *
FROM `table_1` AS `s`
LEFT JOIN `table_2` AS `s0` ON `s`.`table_2_id` = `s0`.`id`
LEFT JOIN `table_3` AS `s1` ON `s0`.`table_3_id` = `s1`.`id`
WHERE (`s`.`date` <= DATE_ADD(UTC_TIMESTAMP(), INTERVAL CAST(`s0`.`validity_months` AS signed) month)))
AND (`s`.`date` >= DATE_ADD(UTC_TIMESTAMP(), INTERVAL CAST(`s0`.`validity_months` * -1 AS signed) month));
This ran into MySQL throws the same error. The problem is at
CAST(`s0`.`validity_months` * -1 AS signed)
How do I negate a field in LINQ. This feels like it's a EFCore bug, but I am not sure yet.

Sql to Slick Conversion

I am converting SQL queries to slick DSL. I am stuck in timestamp conversion.
My SQL query is:
Select isActive from users where create_time <= TIMESTAMPADD(MINUTE,
${AUTO_EXPIRY_DB_DAYS * HOURS_24 * MINUTES_60}, sysdate())
and isVerified=false;
How to write a slick query for the same?
userQuery.filter(user => user.isVerified === FALSE && user.createdDate
<= ?????).map(_.isActive)
Take a look at scalar database functions slick documentation. I suppose this should work:
val sysdate = SimpleLiteral[java.sql.Timestamp]("sysdate")
val timestampAdd = SimpleFunction.ternary[String, Int, java.sql.Timestamp, java.sql.Timestamp]("TIMESTAMPADD")
userQuery
.filter(user => user.isVerified === FALSE
&& user.createdDate <= timestampAdd("MINUTE", 20, sysdate))
.map(_.isActive)

TSQL works in query analyzer but fails as a job step

I have a multi step job that has worked fine for months. All of the sudden it is failing on step 5. If I run the tsql for step 5 in query analyzer it works just fine. Any thoughts? Below is the code I am using.
MERGE BISS..tblBoxInfo AS target
USING ( SELECT BX.BOX_BOXNO, BX.BOX_UDF_AIRR_BOXNO, CONVERT(VARCHAR(510), BX.BOX_DESC),
--RTRIM(STUFF(CONVERT(VARCHAR(510),BOX_DESC), 1,
PATINDEX(N'%[^' + CHAR(9)+CHAR(10)+CHAR(13)+CHAR(32) + N']%', BOX_DESC)-1, N' '))
BX.BOX_UDF_NARA_LOCATION, CONVERT(VARCHAR(6),DP.DEPT_ID),
DP.DEPT_NAME, BX.BOX_UBN, BX.BOX_RCID, CONVERT(VARCHAR(15),CLV.CLV_TITLE),
BX.BOX_DT_CREATION,
CONVERT(VARCHAR(MAX), BX.BOX_UDF_TRIBES),--was NOS = CASE BOX_SROOM_INDEX WHEN 19 THEN 1 ELSE 0 END,
BX.BOX_DT_FROM, BX.BOX_DT_TO, SS.SROOM_ID
FROM ISTAbq3Ver01.VssEnt.dbo.BOXES BX
LEFT JOIN ISTAbq3Ver01.VssEnt.dbo.DEPTS DP
ON DP.DEPT_ID_FULL = BX.BOX_DEPT
LEFT JOIN ISTAbq3Ver01.VssEnt.dbo.SROOMS SS
ON SS.SROOM_AUTO_INDEX = BX.BOX_SROOM_INDEX
LEFT JOIN ISTAbq3Ver01.VssEnt.dbo.CUSTOM_LISTS_VALUES CLV
ON CLV.CLV_AUTO_INDEX = BX.BOX_UDF_AIRR_WORKSITE
WHERE NOT ( SS.SROOM_ID IN (
N'MP',
N'INDEX',
N'QC1',
N'QC2',
N'NTEMP',
N'SF135',
N'SFPREP',
N'NOS',
N'RR',
N'NTEMP2',
N'OHTA',
N'DUPS 36',
N'RSH',
N'DISC',
N'NARAT',
N'TRANS',
N'ABQ')
OR SS.SROOM_ID LIKE N'PGRS-%')
--WHERE SS.SROOM_ID IN (N'NOS', N'NARA')
-- OR SS.SROOM_ID LIKE 'SL%'
/*ORDER BY BOX_BOXNO */) AS source
(BoxID,BoxNum,BoxTitle,BoxLocation,BoxSourceCode,BoxSource,OST,FRC,WorkSite,dtLoaded,TribeInfo,dtFrom,dtTo, BoxStatus)
ON (target.BoxID = source.BoxID)
WHEN MATCHED AND (target.BoxNumber != source.BoxNum
OR target.BoxTitle != source.BoxTitle
OR target.BoxLocation != source.BoxLocation
OR target.BoxSourceCode != source.BoxSourceCode
OR target.BoxSource != source.BoxSource
OR target.OSTNumber != source.OST
OR target.FRCNumber != source.FRC
OR target.WorkSite != source.WorkSite
OR target.LoadedDate != source.dtLoaded
OR target.TribeInfo != source.TribeInfo
OR target.From_Date != source.dtFrom
OR target.To_Date != source.dtTo
OR target.BoxStatus != source.BoxStatus )
THEN UPDATE SET BoxNumber = source.BoxNum,
BoxTitle = source.BoxTitle,
BoxLocation = source.BoxLocation,
BoxSourceCode = source.BoxSourceCode,
BoxSource = source.BoxSource,
OSTNumber = source.OST,
FRCNumber = source.FRC,
WorkSite = source.WorkSite,
LoadedDate = source.dtLoaded,
TribeInfo = source.TribeInfo,
From_Date = source.dtFrom,
To_Date = source.dtTo,
BoxStatus = source.BoxStatus
WHEN NOT MATCHED THEN
INSERT (BoxID,BoxNumber,BoxTitle,BoxLocation,
BoxSourceCode,BoxSource,OSTNumber,FRCNumber,
WorkSite,LoadedDate,TribeInfo,From_Date,To_Date, BoxStatus)
VALUES (source.BoxID,source.BoxNum,source.BoxTitle,source.BoxLocation,
source.BoxSourceCode,source.BoxSource,source.OST,source.FRC,
source.WorkSite,source.dtLoaded,source.TribeInfo,source.dtFrom,source.dtTo, BoxStatus)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
--OUTPUT deleted.*, $action, inserted.*, GETDATE() INTO BISS_Historical..LogTblBoxInfo;
SELECT ##ROWCOUNT

How to write a Linq query equivalent to this SQL

I'm trying to figure out how to write a linq query that will return equivalent results to the sql query below. The problem I'm having has to do with the two select count queries included in the select list of the main query. I need to get counts of two different types of records from the PaymentHistory table for the last year. Can the equivalent of this be written using linq? Preferrably using lambda syntax.
select ieinum, serviceaddrkey,
(select count(*) from PaymentHistory where serviceaddrid = serviceaddrkey
and PostDate >= DateAdd(year, -1 , GetDate())
and SetID = 100) as ReturnedFees,
(select count(*) from PaymentHistory where serviceaddrid = serviceaddrkey
and PostDate >= DateAdd(year, -1 , GetDate())
and SetID = 101) as CorrectedReturnedFees
from Serviceaddr
Any help will be great.
Perhaps something like this:
from s in Serviceaddr
let ph = PaymentHistory.Where(p => s.serviceaddrkey == p.serviceaddrkey &&
p.PostDate >= DateTime.Now.AddYears(-1))
select new
{
s.ieinum,
s.serviceaddrkey,
ReturnedFees = ph.Count(p => p.SetID == 100),
CorrectedReturnedFees = ph.Count(p => p.SetID == 101)
}

Beginner LINQ syntax question

I have a basic SQL Table ( pKey INT, TransDate smallDateTime, Amount Float)
I simply want to emulate this SQL in LINQ
SELECT SUM(Amount) AS result
FROM dbo.Basic
WHERE TransDate >= #startDate
AND TransDate <= #EndDate
I have created the LINQ dbml for this and I can get basic query results for a date range
However I can't find the right syntax to get the SUM over a dateRange, I've tried several variations on the following but either they dont compile, or the result they give cannot be converted to a double
BasicDataContext dContext = new BasicDataContext();
var lnq = from c in dContext.Basic
where c.TransDate >= startdate &&
c.TransDate <= enddate
select new { total = c.Sum(Amount) };
double result = (double)lnq.total;
This should work:
double result = (from c in dContext.Basic
where c.TransDate >= startdate &&
c.TransDate <= enddate
select c.Amount).Sum();