Get January Date Month Record - mysql

i need help on my query . i was trying to generate a list from January to Febuary. however on my query im not sure which part that i did wrong or mistake its only grab Febuary record. Kindly advise . Thanks you
set #FirstDateOfNextMth = CONVERT(varchar,dateadd(d,-(day(dateadd(m,1,getdate()-2))),dateadd(m,1,getdate())),112)
set #LastDateOfNextMth = CONVERT(varchar,dateadd(d,-(day(dateadd(m,2,getdate()))),DATEADD(m,2,getdate())),112)
--------------------------------------------------
INSERT INTO [dbo].[ProcessLog] ([LogTime] ,[LogDescription] ,[LogRemark])
VALUES (GETDATE(), 'Import Client Info', '')
--------------------------------------------------
SET #sSQL = 'SELECT DISTINCT CHDR.CHDRNUM, ZTRN.CCDATE, CHDR.CRDATE, CLNT.CLNTNUM, CLNT.SURNAME, CLNT.GIVNAME,
CLNT.SECUITYNO, ZCLN.EMAIL from (((MPIDTA.ZTRNPF AS ZTRN
LEFT JOIN MPIDTA.CHDRPF AS CHDR ON ZTRN.RLDGACCT = CHDR.CHDRNUM AND ZTRN.EFFDATE = CHDR.CURRFROM)
LEFT JOIN MPIDTA.CLNTPF AS CLNT ON CHDR.COWNNUM = CLNT.CLNTNUM)
LEFT JOIN MPIDTA.ZCLNPF AS ZCLN ON CLNT.CLNTNUM = ZCLN.CLNTNUM)
where (ZTRN.BATCPFX = ''BA'' AND ZTRN.BATCCOY = ''1''
AND ZTRN.CNTTYPE = ''PTB'' AND ZTRN.TRANDATE >= ''20140101''
AND (ZTRN.EXPIRY_DATE BETWEEN ' + #FirstDateOfNextMth + ' AND ' + #LastDateOfNextMth + '))
AND (CHDR.MPLNUM = '''' AND CHDR.CHDRPFX = ''CH''
AND CHDR.CHDRCOY = ''1'' AND CHDR.VALIDFLAG = ''1'')'
SET #sExe = 'Insert into dbo.TPA_Client_Info Select * FROM OPENQUERY(AS400, ''' + REPLACE(#sSQL, '''', '''''') + ''')'
exec (#sExe)

Problem is in #FirstDateOfNextMth.
set #FirstDateOfNextMth = CONVERT(varchar,dateadd(d,-(day(dateadd(m,1,getdate()-2))),
dateadd(m,1,getdate())),112)
Result is 20150202
since the #FirstDateOfNextMth is 20150202 in where condition ZTRN.EXPIRY_DATE is filtered between feb month alone. Try changing like this.
set #FirstDateOfNextMth = DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)

Related

MySQL pass a variable string argument to stored procedure variable

I have the following stored procedure:
CREATE DEFINER=`sleuser`#`%` PROCEDURE `PCDD`(
in ProjectID int,
in MonthName varchar(50),
in ServiceCode varchar(50),
in ProjectName varchar(50)
)
BEGIN
SET #PCProjID = ProjectID;
SET #PCSN1 = "020." + ServiceCode + ".000";
SET #Month = MonthName;
SET #ImpCostID = ProjectName;
SET #ImpCostTask1 = "020." + ServiceCode + ".000";
SELECT
project.project_id,
'FP' as Phase,
ImportCost.OriginalCommitments,
ImportCost.ApprovedCommitmentChanges,
sum(RegisteredChangeOrders) + sum(OriginalContractPrice) as CurrentAssigned,
sum(ProjectCostBudget.PendingChangeOrders) as PendingScopeChanges,
FROM `RCLY-DEV`.ProjectCostBudget
inner join project on project.project_id =
ProjectCostBudget.ProjectID
inner join ImportCost on ImportCost.ProjectID = project.pmis
where ImportCost.ProjectID = #ImpCostID and
ImportCost.Task = #PCSN1 and
ProjectCostBudget.ProjectID = #PCProjID and
ProjectCostBudget.ServiceNumber = #ImpCostTask1
which i call using:
call PCDD(2,'September%2018','0000','RLCY-BB-01')
Where '0000' needs to vary from '0000' to '6000'. When I run the SP for '0000' it returns the expected results, but when I change it to anything else it just returns all nulls. I tried updating #PCSN1 and #ImpCostTask1 to:
SET #PCSN1 = ("020.", ServiceCode, ".000");
SET #ImpCostTask1 = ("020.", ServiceCode, ".000");
But i get the error
"Operand should contain 1 column(s).
What am i doing wrong here? Why does it work for one ServiceCode but not the others?
You need to use ' enqoute string literal and CONCAT instead of '+' for string concatenation:
SET #PCSN1 = "020." + ServiceCode + ".000";
=>
SET #PCSN1 = CONCAT('020.', ServiceCode, '.000');
Same for:
SET #ImpCostTask1 = "020." + ServiceCode + ".000";
=>
SET #ImpCostTask1 = CONCAT('020.', ServiceCode, '.000');

insert into... on duplicate update causes Unknown column in field list, but the field exists

I am getting the error "Error Code: Unknown column 't2.FSVisitsToDate' in 'field list' when I run my query but I cannot figure out where my query is wrong. Can anyone point out what I did wrong?
INSERT INTO CMCustomer
(CustomerNumber,
LastName,
FirstName,
Address,
City,
State,
ZIPCode,
PhoneNo,
DriverLicenseNo,
SocialSecNo,
TaxExempt,
ExternalRefNumber,
AuxField,
Comments,
FSLevelNo,
FSDateOpened,
FSLastVisit,
FSVisitsToDate,
FSVisitsThisPeriod,
FSPurchaseToDate,
FSPurchaseThisPeriod,
FSDiscountToDate,
FSDiscountThisPeriod,
FSPointsToDate,
FSPointsThisPeriod,
FSPromoPointsToDate,
FSPromoPointsThisPeriod,
LastUpdated,
Employee)
SELECT t1.CustomerNumber,
t1.LastName,
t1.FirstName,
t1.Address,
t1.City,
t1.State,
t1.ZIPCode,
t1.PhoneNo,
t1.DriverLicenseNo,
t1.SocialSecNo,
t1.TaxExempt,
t1.ExternalRefNumber,
t1.AuxField,
t1.Comments,
t1.FSLevelNo,
t1.FSDateOpened,
t1.FSLastVisit,
t1.FSVisitsToDate,
t1.FSVisitsThisPeriod,
t1.FSPurchaseToDate,
t1.FSPurchaseThisPeriod,
t1.FSDiscountToDate,
t1.FSDiscountThisPeriod,
t1.FSPointsToDate,
t1.FSPointsThisPeriod,
t1.FSPromoPointsToDate,
t1.FSPromoPointsThisPeriod,
t1.LastUpdated,
t1.Employee
FROM cm01process t1
LEFT JOIN CMCustomer t2 ON t2.CustomerNumber = t1.CustomerNumber
ON DUPLICATE KEY UPDATE
t2.FSVisitsToDate = t2.FSVisitsToDate + t1.FSVisitsToDate,
t2.FSVisitsThisPeriod = t2.FSVisitsThisPeriod + t1.FSVisitsThisPeriod,
t2.FSPurchaseToDate = t2.FSPurchaseToDate + t1.FSPurchaseToDate,
t2.FSPurchaseThisPeriod = t2.FSPurchaseThisPeriod + t1.FSPurchaseThisPeriod,
t2.FSDiscountToDate = t2.FSDiscountToDate + t1.FSDiscountToDate,
t2.FSDiscountThisPeriod = t2.FSDiscountThisPeriod + t1.FSDiscountThisPeriod,
t2.FSPointsToDate = t2.FSPointsToDate + t1.FSPointsToDate,
t2.FSPointsThisPeriod = t2.FSPointsThisPeriod + t1.FSPointsThisPeriod,
t2.FSPromoPointsToDate = t2.FSPromoPointsToDate + t1.FSPromoPointsToDate,
t2.FSPromoPointsThisPeriod = t2.FSPromoPointsThisPeriod + t1.FSPromoPointsThisPeriod;
What I am trying to accomplish is to take a file from one of my stores and import it to my database. If it is a new customer I need the row added, and if it is a duplicate customer I need fields updated (points added to the user).
I am not sure why this worked so I would love someone to explain so I have a better understanding but apparently the query completes successfully if I structure the "on duplicate..." part of the statement like so:
ON DUPLICATE KEY UPDATE
CMCustomer.FSVisitsToDate = CMCustomer.FSVisitsToDate + values(FSVisitsToDate),
CMCustomer.FSVisitsThisPeriod = CMCustomer.FSVisitsThisPeriod + values(FSVisitsThisPeriod),
CMCustomer.FSPurchaseToDate = CMCustomer.FSPurchaseToDate + values(FSPurchaseToDate),
CMCustomer.FSPurchaseThisPeriod = CMCustomer.FSPurchaseThisPeriod + values(FSPurchaseThisPeriod),
CMCustomer.FSDiscountToDate = CMCustomer.FSDiscountToDate + values(FSDiscountToDate),
CMCustomer.FSDiscountThisPeriod = CMCustomer.FSDiscountThisPeriod + values(FSDiscountThisPeriod),
CMCustomer.FSPointsToDate = CMCustomer.FSPointsToDate + values(FSPointsToDate),
CMCustomer.FSPointsThisPeriod = CMCustomer.FSPointsThisPeriod + values(FSPointsThisPeriod),
CMCustomer.FSPromoPointsToDate = CMCustomer.FSPromoPointsToDate + values(FSPromoPointsToDate),
CMCustomer.FSPromoPointsThisPeriod = CMCustomer.FSPromoPointsThisPeriod + values(FSPromoPointsThisPeriod);
I think that you can reference the table you are inserting into and the table you are inserting from must use VALUES() Can anyone confirm?

Error when choosing values in the Pre-Filtering Windows

Recently have designed a SSRS report for CRM 2011 on-premise using the #CRM_EntityName parameters to enable the Prefiltering option. But for some strange reason when I choose any value on the prefiltering window the report exits with an exception. Then I created a SQL Profiler and this is what the SQL receive:
exec sp_executesql N'declare #binUserGuid varbinary(128)
declare #userGuid uniqueidentifier
select #userGuid = N''{552d241b-0347-e311-9f1e-00155d039706}''
set #binUserGuid = cast(#userGuid as varbinary(128))
set context_info #binUserGuid;
DECLARE #SQL2 AS nVarchar(max)
SET #SQL2 = ''SELECT StudentsRecords.xrmsm_students_id, StudentsRecords.xrmsm_studentsfullname, StudentProgress.TotalPoints, StudentProgress.PointsObtained,
StudentProgress.xrmsm_subjectscode, StudentProgress.Average,
CASE WHEN StudentProgress.Average >= 90 THEN ''''AN'''' WHEN StudentProgress.Average >= 80 THEN ''''PR'''' WHEN StudentProgress.Average >= 60 THEN ''''EP'''' WHEN StudentProgress.Average
> - 1 THEN ''''I'''' ELSE NULL END AS Progress, CONVERT(nvarchar(50), StudentsRecords.xrmsm_studentsid) + StudentProgress.xrmsm_subjectscode AS VLookupData,
StudentsRecords.xrmsm_studentsgrade, StudentsRecords.xrmsm_studentsgradename as Value
FROM Filteredxrmsm_students AS StudentsRecords INNER JOIN
(SELECT st.xrmsm_studentsid, su.xrmsm_subjectscode,
SUM(sc.xrmsm_scoresresults) AS PointsObtained, SUM(eva.xrmsm_evaluationstotal) AS TotalPoints,
SUM(sc.xrmsm_scoresresults) / SUM(eva.xrmsm_evaluationstotal) * 100.00 AS Average
FROM Filteredxrmsm_scores as sc INNER JOIN
Filteredxrmsm_evaluations as eva ON sc.xrmsm_evaluationlookup = eva.xrmsm_evaluationsid INNER JOIN
Filteredxrmsm_students as st ON sc.xrmsm_studentlookup = st.xrmsm_studentsid INNER JOIN
(''
+ #CRM_Filteredxrmsm_sessions + '')
AS se ON
se.xrmsm_sessionsid = eva.xrmsm_sessionlookup INNER JOIN
Filteredxrmsm_institutionCourses as ic ON
ic.xrmsm_institutioncoursesid = se.xrmsm_institutioncourselookup INNER JOIN
Filteredxrmsm_courses as co ON co.xrmsm_coursesid = ic.xrmsm_courselookup INNER JOIN
(''
+ #CRM_Filteredxrmsm_subjects + '') AS su ON
su.xrmsm_subjectsid = co.xrmsm_subjectlookup INNER JOIN
Filteredxrmsm_sessionEnrollments as sen ON sen.xrmsm_studentlookup = sc.xrmsm_studentlookup AND
eva.xrmsm_sessionlookup = se.xrmsm_sessionsid AND
eva.xrmsm_termsessionlookup = sen.xrmsm_termsessionlookup INNER JOIN
(''
+ #CRM_Filteredxrmsm_educationalstructure + '') as ed ON
eva.xrmsm_yearlookup = ed.xrmsm_yearlookup AND
se.xrmsm_institutionlookup = ed.xrmsm_institutionlookup AND
ed.xrmsm_programlookup = se.xrmsm_programlookup
WHERE (eva.xrmsm_evaluationsdate >= ''''''+ convert(varchar(10),#termStartDate,120) + '''''') AND (eva.xrmsm_evaluationsdate <= ''''''+ convert(varchar(10),#monthReport,120) + '''''')
AND (eva.statuscode = 1) AND (sc.statuscode = 1) AND (st.statuscode = 1) AND
(se.statuscode = 1) AND (sen.statuscode = 1) AND
(ed.statuscode = 1)
GROUP BY st.xrmsm_studentsid, su.xrmsm_subjectscode) AS StudentProgress ON
StudentsRecords.xrmsm_studentsid = StudentProgress.xrmsm_studentsid''
EXEC (#SQL2)',N'#CRM_Filteredxrmsm_educationalstructure nvarchar(114),#CRM_Filteredxrmsm_sessions nvarchar(78),#CRM_Filteredxrmsm_subjects nvarchar(165),#termStartDate datetime,#monthReport datetime',#CRM_Filteredxrmsm_educationalstructure=N'select
[xrmsm_educationalstructure0].*
from
Filteredxrmsm_educationalstructure as "xrmsm_educationalstructure0"',#CRM_Filteredxrmsm_sessions=N'select
[xrmsm_sessions0].*
from
Filteredxrmsm_sessions as "xrmsm_sessions0"',#CRM_Filteredxrmsm_subjects=N'select
[xrmsm_subjects0].*
from
Filteredxrmsm_subjects as "xrmsm_subjects0"
where
("xrmsm_subjects0".xrmsm_subjectsid = N''0FE2990A-1847-E311-9F1E-00155D039706'')',#termStartDate='2014-01-01 00:00:00',#monthReport='2014-01-31 00:00:00'
When I run this statement directly on SQL I receive the following error:
Msg 4145, Level 15, State 1, Line 44
An expression of non-boolean type specified in a context where a condition is expected, near 'Student'.
I dont know what could be the problem.
Thanks for all the views. I already solved the problem. My solution was make the dataset with the subquery part then i make the calculations in the report.

update query based on select query

exactly I want to write "UPDATE" and "SELECT" into one query.
I need check for setting a field.
for this action, I used SELECT query on TABLE1 and then if it dose not have result, another filed of TABLE2 is updated.
FOR EX:
$res = mysqli_query($con , "select sID FROM schedule where (dayID = '{$this->dID}' AND patientID = '')");
$rep = mysqli_fetch_array($res);
if(count($rep) == 0)
mysqli_query($con,"update days set schFilled = 1 where dID = '{$this->dID}'");
else
mysqli_query($con,"update days set schFilled = 0 where dID = '{$this->dID}'");
I would like run those with ONE query, in fact I want something like this:(whit CASE to write second update too)
update days set schFilled = 0 where( (select sID FROM schedule where (dayID = '{$this->dID}' AND patientID = '') IS NULL) AND (dID = '{$this->dID}'))
use the mysqli object like this:
$res = mysqli_query($con , "your select");
if($res->num_rows === 0) {
//no res
}
else {
//else
}
"UPDATE days SET schFilled =
CASE
WHEN (SELECT IF(EXISTS(select sID FROM schedule where (dayID = '{$this->dID}' AND patientID = '' AND hour != 0)), 1, 0))
THEN 0
ELSE 1
END
where dID = '{$this->dID}'"

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