TSQL works in query analyzer but fails as a job step - sql-server-2008

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

Related

How to Add and Compare Results from Subqueries

I have the following code written for a larger report that I have been working on. I have three columns resulting from subqueries: req_hrs, e_hrs, inprog_hrs. I need to add together the e_hrs and inprog_hrs, thus seeing whether that number is greater than or equal to req_hrs. If that is true, I need to return either an * or a null value.
Can someone please explain to me how I can add the two subquery results (e_hrs and inprog_hrs) together, and then compare that result to req_hrs thus returning said * or NVL? Code is below, Thank you:
SELECT
spriden_last_name lname,
spriden_first_name fname,
spriden_mi mi,
spriden_id id,
x.shrdgmr_majr_code_1 majr,
x.shrdgmr_grad_date grad_dt,
x.shrdgmr_degs_code degs,
DECODE(stvdegs_award_status_ind,'A','*',NULL) award_ind,
**DECODE(NVL(m.smbagen_req_credits_overall,0),0,
DECODE(NVL(sorcmjr_req_hours_ssdf,0),0,
DECODE(stvdegc_acat_code,'22',32,'23',64,'24',124,'42',42,999),
sorcmjr_req_hours_ssdf),m.smbagen_req_credits_overall) req_hrs,**
**TRUNC(shrlgpa_hours_earned,2) AS e_hrs,**
**(SELECT
NVL(SUM(sfrstcr_credit_hr),0)
FROM
sfrstcr
WHERE
sfrstcr_term_code = '&inprog_term'
AND sfrstcr_pidm = x.shrdgmr_pidm
AND sfrstcr_rsts_code IN ('RE','RW')
AND NOT EXISTS (
SELECT
'Y'
FROM
shrtckn,
shrtckg j
WHERE
shrtckn_pidm = sfrstcr_pidm
AND shrtckn_term_code = sfrstcr_term_code
AND shrtckn_crn = sfrstcr_crn
AND j.shrtckg_pidm = shrtckn_pidm
AND j.shrtckg_term_code = shrtckn_term_code
AND j.shrtckg_tckn_seq_no = shrtckn_seq_no
AND j.shrtckg_seq_no = (
SELECT
MAX(k.shrtckg_seq_no)
FROM
shrtckg k
WHERE
k.shrtckg_pidm = shrtckn_pidm
AND k.shrtckg_term_code = shrtckn_term_code
AND k.shrtckg_tckn_seq_no = shrtckn_seq_no))) AS inprog_hrs,**
ROUND(shrlgpa_gpa,2) gpa,
DECODE(SIGN(shrlgpa_gpa - 3.90),0,'S',1,'S',
DECODE(SIGN(shrlgpa_gpa - 3.75),0,'M',1,'M',
DECODE(SIGN(shrlgpa_gpa - 3.50),0,'C',1,'C',NULL))) latin,
(SELECT
m.shrasdl_astd_code_dl
FROM
shrasdl m
WHERE
m.shrasdl_term_code_effective = (
SELECT
MAX(n.shrasdl_term_code_effective)
FROM
shrasdl n)
AND m.shrasdl_min_gpa_term = (
SELECT
MAX(n.shrasdl_min_gpa_term)
FROM
shrasdl n
WHERE
n.shrasdl_term_code_effective = m.shrasdl_term_code_effective
AND shrlgpa_gpa >= n.shrasdl_min_gpa_term)) honors
FROM
shrdgmr x,
stvdegs,
stvdegc,
spriden,
sorcmjr,
smbagen m,
shrlgpa
WHERE
TO_CHAR(x.shrdgmr_grad_date,'MON-YY') IN ('&grad_dt1', NVL('&grad_dt2','XXX-
00'))
AND x.shrdgmr_seq_no = (
SELECT
MAX(z.shrdgmr_seq_no)
FROM
shrdgmr z
WHERE
z.shrdgmr_pidm = x.shrdgmr_pidm
AND z.shrdgmr_majr_code_1 = x.shrdgmr_majr_code_1
AND z.shrdgmr_grad_date IS NOT NULL)
AND stvdegs_code = x.shrdgmr_degs_code
AND stvdegc_code = x.shrdgmr_degc_code
AND spriden_pidm = x.shrdgmr_pidm
AND spriden_change_ind IS NULL
AND sorcmjr_cmjr_rule(+) = x.shrdgmr_cmjr_rule_1_1
AND REPLACE(m.smbagen_area(+),'-CORE','') = x.shrdgmr_majr_code_1
AND m.smbagen_active_ind(+) = 'Y'
AND m.smbagen_term_code_eff(+) <= x.shrdgmr_term_code_grad
AND ((m.smbagen_area IS NULL)
OR (m.smbagen_area IS NOT NULL
AND m.smbagen_term_code_eff = (
SELECT
MAX(n.smbagen_term_code_eff)
FROM
smbagen n
WHERE
REPLACE(n.smbagen_area,'-CORE','') = x.shrdgmr_majr_code_1
AND n.smbagen_active_ind = 'Y'
AND n.smbagen_term_code_eff <= x.shrdgmr_term_code_grad)))
AND shrlgpa_pidm(+) = x.shrdgmr_pidm
AND shrlgpa_levl_code(+) = x.shrdgmr_levl_code
AND shrlgpa_gpa_type_ind(+) = 'O'
ORDER BY
spriden_last_name,
spriden_first_name,
spriden_mi
;
Compare the sum of the union of the two sources with the required amount.
In simplified form:
select somekey, sum(hrs) worked_hrs, sum(req_hrs) required_hrs
from (
select
somekey,
e_hrs hrs
from e_hrs_table
where ...
union all -- the "all" is important to leave in!
select
somekey,
inprog_hrs
from inprog_hrs_table
where ...
) x
join req_hrs_table on req_hrs_table.somekey = x.somekey
where ... -- add req_hrs_table conditions here
group by somekey
You can add
having sum(hrs) < sum(req_hrs)
if you want only those rows that did not meet the quota.

How to use IF() and ELSE () statements in MYSQL

I want to DELETE data OR UPDATE data in MYSQL. such that if column message_deleted_by is found in a string IN() then the query should delete rows where the WHERE clause(filtering) is true ELSE the query should update message_table column message_deleted_by with some data ....ALL IN THE SAME QUERY
if this can be achieved please help.
I'v tried and tried but it output errors.
$token = mysqli_real_escape_string($dbc_conn,encode64(getsecreteToken($_POST["token"])));
$mid = mysqli_real_escape_string($dbc_conn,$_POST["mid"]);
$rid = mysqli_real_escape_string($dbc_conn,$_POST["rid"]);
$sid = mysqli_real_escape_string($dbc_conn,$_POST["sid"]);
$group = implode(",",array($rid,$sid));
$IsLoggIn = '2';
$SQL = "
IF(
SELECT message_deleted_by AS mdb FROM $message_tatable
WHERE (
m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
) AND
m.token='$token' AND m.id='$mid'
) mdb IN($group) THEN
DELETE m,mf
FROM $message_tatable m
LEFT JOIN $message_files_tb mf ON
m.token=mf.token
WHERE (
m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
) AND
m.token='$token' AND m.id='$mid';
ELSE
UPDATE $message_tatable SET message_deleted_by='$IsLoggIn'
WHERE (
m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
) AND
m.token='$token' AND m.id='$mid';
END IF;
";
//QUERY database
$query = mysqli_query($dbc_conn,$SQL);
die(mysqli_error($dbc_conn));
Try this,
UPDATE $message_tatable m
LEFT JOIN $message_files_tb mf
ON m.token=mf.token
SET m=NULL,
mf=NULL
WHERE m OR mf=SELECT message_deleted_by FROM $message_tatable IN($group)
AND m.sender_id='$IsLoggIn' AND m.recipient_id='$rid'
AND m.token='$token' AND m.id='$mid'

How to make function execute faster in SQL?

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.

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}'"