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');
Related
I'm having trouble calling a function and using the value from the function call within my stored procedure using mySQL. My function extracts a date value. I'm attempting to set the parameter values with my stored procedure call (parameters - data_transfer_id, mode). Is this possible?
Your help is appreciated. My code below is incorrect but is my start. The function name is kettle_data_transfer.f_DT_last_transfer (data_transfer_id, mode).
CREATE PROCEDURE `sproc_DT_consumer_answer_data`
(IN data_transfer_id bigint (20),
IN `mode` varchar(25)
)
BEGIN
DECLARE last_transfer date kettle_data_transfer.f_DT_last_transfer(data_transfer_id, mode);
SELECT
CEQ.consumer_ID
, EM.event_mapping_ID
, F.footprint_ID
, F.create_DTM as footprint_create_DTM
, EM.event_ID
, EL.brand_ID
, RELAT.activity_type_ID
, ED.event_ID as footprint_event_ID
FROM kettle_data_transfer.Event_Mappings EM
JOIN kettle_data_transfer.Consumer_Event_Queue CEQ ON CEQ.event_ID = EM.event_ID
JOIN efn.Footprints F ON F.consumer_ID = CEQ.consumer_ID
LEFT OUTER JOIN efn.Event_Days ED on ED.event_day_ID = F.event_day_ID
LEFT OUTER JOIN efn.R_Event_Location_Activity_Type RELAT ON RELAT.r_elat_ID = F.r_elat_ID
LEFT OUTER JOIN efn.Event_Locations EL on EL.event_location_ID = RELAT.event_location_ID
LEFT OUTER JOIN kettle_data_transfer.Records RR on RR.consumer_ID = CEQ.consumer_ID
WHERE EM.active_flag = 1
AND F.sample_flag = 0
AND RR.failure_code = 0
AND RR.`ignore` = 0
and (CEQ.modify_DTM > last_transfer OR EM.create_DTM > last_transfer)
and (RR.mode = `mode` OR EM.mode = `mode`)
and (RR.data_transfer_ID = data_transfer_id OR EM.data_transfer_ID = data_transfer_id )
and (RR.consumer_ID = CEQ.consumer_ID)
AND (ED.event_ID = CEQ.event_ID OR ED.event_ID is null)
GROUP BY CEQ.consumer_ID, EL.brand_ID
END
The syntax for stored program variable declarations:
DECLARE var_name [, var_name] ... type [DEFAULT value]
DEFAULT value is not saying "default value goes here." It's the keyword DEFAULT, followed by an expression containing the initial value for the variable.
You are trying to set the default initial value of the variable, but you have omitted the DEFAULT keyword after the variable name.
Adding it should resolve the issue.
https://dev.mysql.com/doc/refman/5.6/en/declare-local-variable.html
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)
I am using function to update to one column , like
DetailedStatus = dbo.fn_GetProcessStageWiseStatus(PR.ProcessID, PR.ProcessRunID, getdate())
Here 500,000 records are continuously UPDATED in this line. Its like like a loop
So using this function for few records its executing fast but when its 500,000 records executing it becomes very slow...
What can I do to make this execute faster using many records?
Any measures to be taken or any split to be used?
Function:
CREATE FUNCTION [dbo].[fn_GetProcessStageWiseStatus]
(
#ProcessID INT
,#ProcessRunID INT
,#SearchDate SMALLDATETIME
)
RETURNS VARCHAR(100)
AS
BEGIN
DECLARE
#iLoopCount SMALLINT
,#iRowCount SMALLINT
,#StepProgress VARCHAR(100)
,#StepCount SMALLINT
IF EXISTS(
SELECT TOP 1 1
FROM dbo.Step S WITH(NOLOCK)
JOIN dbo.vw_FileGroup FG
ON S.FileConfigGroupID = FG.FileConfigGroupID
WHERE S.ProcessID = #ProcessID
AND S.Active = 1
AND FG.FileConfigGroupActive = 1
AND FG.Direction = 'Inbound'
)
BEGIN
SET #StepProgress = 'Not Received'
END
ELSE
BEGIN
SET #StepProgress = 'Not Started'
END
DECLARE #StepRunDetailsTable TABLE
(
KeyNo INT IDENTITY(1,1)
,StepID INT
,StepStartTime SMALLDATETIME
,StepEndTime SMALLDATETIME
,SourceEnv VARCHAR(100)
,DestEnv VARCHAR(100)
)
INSERT INTO #StepRunDetailsTable
SELECT
S.StepID
,MAX(isnull(SR.StepStartTime, '06/06/2079'))
,MAX(isnull(SR.StepEndTime, '06/06/2079'))
,isnull(SENV.EnvironmentName, '')
,isnull(DENV.EnvironmentName, '')
FROM dbo.ProcessRun PR WITH(NOLOCK)
JOIN dbo.StepRun SR WITH(NOLOCK)
ON SR.ProcessRunID = PR.ProcessRunID
JOIN dbo.vw_StepHierarchy SH
ON SR.StepID = SH.StepID
AND SH.Active = 1
JOIN dbo.Step S WITH(NOLOCK)
ON SH.StepID = S.StepID
JOIN dbo.WorkFlow WF WITH(NOLOCK)
ON S.WorkFlowID = WF.WorkFlowID
AND WF.Active = 1
JOIN dbo.Environment SENV WITH(NOLOCK)
ON SENV.EnvironmentID = WF.SourceEnvironmentID
AND SENV.Active = 1
JOIN dbo.Environment DENV WITH(NOLOCK)
ON DENV.EnvironmentID = WF.DestinationEnvironmentID
AND DENV.Active = 1
WHERE PR.ProcessRunID = #ProcessRunID
GROUP BY S.StepID, SENV.EnvironmentName, DENV.EnvironmentName, SH.StepOrder
ORDER BY SH.StepOrder ASC
SELECT #StepCount = COUNT(*)
FROM dbo.ProcessRun PR WITH(NOLOCK)
JOIN dbo.Step S WITH(NOLOCK)
ON PR.ProcessID = S.ProcessID
AND PR.ProcessRunID = #ProcessRunID
AND S.Active = 1
SELECT #iRowCount = COUNT(DISTINCT StepID) FROM #StepRunDetailsTable
SET #iLoopCount = 0
WHILE (#iRowCount > #iLoopCount)
BEGIN
SET #iLoopCount = #iLoopCount + 1
SELECT
#StepProgress =
CASE
--WHEN #SearchDate BETWEEN StepStartTime AND StepEndTime
WHEN #SearchDate >= StepStartTime AND #SearchDate <= StepEndTime
THEN DestEnv + ' Load in Progress'
WHEN #SearchDate > StepEndTime AND #iLoopCount < #StepCount
THEN 'Waiting on next step - Loaded to ' + DestEnv
WHEN #SearchDate > StepEndTime AND #iLoopCount = #StepCount
THEN 'Completed'
WHEN #SearchDate < StepStartTime AND #iLoopCount = 1
THEN 'Load Not Started'
ELSE #StepProgress
END
FROM #StepRunDetailsTable
WHERE KeyNo = #iLoopCount
END
RETURN #StepProgress
END
Thanks in advance.
Seems like you have a change in execution plan when you try to update 500k rows.
You can try and set forceseek hint on the from clause to force using seeks instead of scans.
Also, WHILE (#iRowCount > #iLoopCount) should be replaced with if exists, because you basically check for certain conditions on the results table and you need to return as early as possible.
I see that you use nolock hint everywhere to allow dirty reads, you can set isolation level read uncommitted in the calling stored procedure and remove all of those; or consider to change the database to set read_committed_snapshot on to avoid locks.
By the way, scalar function calls in SQL Server are very expensive, so if you have some massive updates/selects happening in a loop where you call a function you have to avoid using functions as much as possible.
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.
I have a MySQL stored procedure and in it, the following WHILE statement.
I have confirmed that #RowCnt is 1, and #MaxRows is 6090, however after further debugging, I realized that the WHILE statement is going through a single iteration and not continuing; so I'm hoping to have some light shed on what could possibly be causing this.
Full disclosure: I ported this from SQL Server to a MySQL stored procedure, something I have never taken on before. (meaning SQL Server, porting OR stored procedures..)
WHILE #RowCnt <= #MaxRows DO
SELECT #currentReadSeq:=ReadSeq, #currentReadStrength:=ReadStrength, #currentReadDateTime:=ReadDateTime, #currentReaderID:=ReaderID FROM tblTempRead WHERE rownum = #RowCnt;
IF ( ((#lastReadSeq + 10) > #currentReadSeq) AND (#lastReaderId = #currentReaderId) ) THEN
SET #lastReadSeq = #currentReadSeq, #lastReadStrength = #currentReadStrength, #lastReadDateTime = #currentReadDateTime, #lastReaderID = #currentReaderID;
ELSE
INSERT INTO tblreaddataresults (SiteID, ReadDateTimeStart, ReadDateTimeEnd, ReadSeqStart, ReadSeqEnd, ReaderID, DirectSeconds) VALUES ('1002', #saveReadDateTime, #lastReadDateTime, #saveReadSeq, #lastReadSeq, #lastReaderID, timestampdiff(SECOND,#saveReadDateTime,#lastReadDateTime));
SET #saveReadSeq = #currentReadSeq, #saveReadStrength = #currentReadStrength, #saveReadDateTime = #currentReadDateTime, #saveReaderID = #currentReaderID;
SET #lastReadSeq = #saveReadSeq, #lastReadStrength = #saveReadStrength, #lastReadDateTime = #saveReadDateTime, #lastReaderID = #saveReaderID;
END IF;
SET #RowCnt = #RowCnt+1;
END WHILE;
Try This Construct
WHILE (#RowCnt <= #MaxRows)
BEGIN
SELECT #currentReadSeq:=ReadSeq, #currentReadStrength:=ReadStrength, #currentReadDateTime:=ReadDateTime, #currentReaderID:=ReaderID FROM tblTempRead WHERE rownum = #RowCnt;
IF (((#lastReadSeq + 10) > #currentReadSeq) AND (#lastReaderId = #currentReaderId))
BEGIN
SET #lastReadSeq = #currentReadSeq, #lastReadStrength = #currentReadStrength, #lastReadDateTime = #currentReadDateTime, #lastReaderID = #currentReaderID;
END
ELSE
BEGIN
INSERT INTO tblreaddataresults (SiteID, ReadDateTimeStart, ReadDateTimeEnd,ReadSeqStart, ReadSeqEnd, ReaderID, DirectSeconds) VALUES ('1002',#saveReadDateTime, #lastReadDateTime, #saveReadSeq, #lastReadSeq, #lastReaderID,timestampdiff(SECOND,#saveReadDateTime,#lastReadDateTime));
SET #saveReadSeq = #currentReadSeq, #saveReadStrength = #currentReadStrength, #saveReadDateTime = #currentReadDateTime, #saveReaderID = #currentReaderID;
SET #lastReadSeq = #saveReadSeq, #lastReadStrength = #saveReadStrength,#lastReadDateTime = #saveReadDateTime, #lastReaderID = #saveReaderID;
END
SET #RowCnt = #RowCnt+1;
END