Grouping within a While Loop, SQL Server - sql

I've been building a while loop to populate a lot of data, and I'm struggling with grouping within the query - I want to add a group on Membership_Level but each time it is returning identical values (the total) for each Level.
Can anyone help me?
Thank you in advance!!!
DECLARE #Counter int
DECLARE #NumPerson int
SET #Counter = 1
WHILE #Counter <= 12
BEGIN
SET #NumPerson = (SELECT
SUM(Amount)
FROM [NewMember]
WHERE LEFT([PERIOD], 4) = 2016
AND GRADE_STATUS = 'N'
AND RIGHT([Period], 2) = #Counter)
SELECT
*
FROM (SELECT
CAST(#NumPerson AS varchar(6)) AS 'Number',
CASE
WHEN LEN(CAST(#Counter AS varchar(2))) = 1 THEN '0' + CAST(#Counter AS varchar(2))
ELSE CAST(#Counter AS varchar(2))
END AS 'Month') s
JOIN (SELECT
MAX('1') AS NGroup,
[PERIOD],
RIGHT([Period], 2) AS 'Month',
MEMBERSHIP_LEVEL
FROM [NewMember]
WHERE LEFT([PERIOD], 4) = 2016
AND GRADE_STATUS = 'N'
GROUP BY [MEMBERSHIP_LEVEL],
[PERIOD],
RIGHT([Period], 2)) t
ON s.[Month] = t.[Month]
SET #Counter = #Counter + 1
END

Related

Sql query has low performance on SQL server management studio

I hope this year will be great.
I am new to SQL server and i'm trying to display some values with the lower cost. At now, the query gives me the results in almost 17 seconds. I would like to have performance almost 8 to 5 seconds.
This is a query to display data on a graph. I take this query and I insert it into a php file.
I have created indexes so I have succeed from 25 seconds to 17 seconds. I don't know what to do next.
Here is my code:
DECLARE #jahre TABLE(jahr int);
WITH CTE AS
(
SELECT 2013 AS JournalDatum
UNION ALL
SELECT JournalDatum+1
FROM CTE
WHERE JournalDatum < YEAR(GETDATE())
)
INSERT INTO #jahre SELECT * FROM CTE
DECLARE #years4Pivot AS NVARCHAR(MAX),#query AS NVARCHAR(MAX)
SET #years4Pivot = STUFF((SELECT ',' + '['+CAST(jahr AS VARCHAR(4))+ ']' FROM #jahre FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET #query = N'
WITH cashin AS (
SELECT * FROM (
SELECT
/*
dbo.cdGetFDOM(JournalDatum) myDatum
,MONTH(JournalDatum) AS Monat
,jou.KreisLFN
*/
DATENAME(YEAR, JournalDatum) AS Jahr
,jou.ObjektLFN
,CAST(SUM(FibuHabenNetto) as float)-CAST(SUM(FibuSollNetto) as float)-CAST(SUM(FibuMWST) as float) fibuBetrag
,(''NKM_'' + REPLACE(SUBSTRING(EinheitArtBezeichnung,2,2),'')'','''')) EinhArtPos
,mieteig.MietEigLFN
,mieteig.MietEigCode1
FROM
dbo.TF0700_Journal AS jou
JOIN dbo.TF0720_Fibu AS fibu ON fibu.JournalLFN = jou.JournalLFN
JOIN dbo.TF0710_JournalOPPos AS joupos ON joupos.OpPosLFN = fibu.OPPosLFN
JOIN dbo.TA0270_Position AS pos ON pos.PositionLFN = joupos.PositionLFN
JOIN dbo.TA0310_MietEigEinheit ME ON ME.EinheitLFN = joupos.EinheitLFN
JOIN dbo.TZ0310_EinheitArt EA ON ME.EinheitArtLFN = EA.EinheitArtLFN
JOIN dbo.TA0300_MietEig mieteig ON joupos.MietEigLFN = mieteig.MietEigLFN
WHERE
JournalArt = 21
AND pos.PositionArt=1
AND RIGHT(LEFT(MietEigCode1,5),1) NOT IN
(
SELECT MietEigCode1 from TA0300_MietEig
WHERE RIGHT(LEFT(MietEigCode1,5),1) IS NOT NULL
AND RIGHT(LEFT(MietEigCode1,5),1) NOT LIKE '' ''
)
GROUP BY
/*
dbo.cdGetFDOM(JournalDatum) myDatum
,MONTH(JournalDatum) AS Monat
,jou.KreisLFN
*/
DATENAME(YEAR, JournalDatum)
,jou.ObjektLFN
,REPLACE(SUBSTRING(EinheitArtBezeichnung,2,2),'')'','''')
,mieteig.MietEigLFN
,mieteig.MietEigCode1
) AS Q
PIVOT (SUM(fibuBetrag) FOR EinhArtPos IN (NKM_W,NKM_G,NKM_B,NKM_GA,NKM_SP,NKM_S)) P
)
SELECT *
FROM
(
SELECT
/*
--c.myDatum
--,c.Monat
--,c.KreisLFN
*/
c.Jahr as Jahr
,c.ObjektLFN
,ISNULL(NKM_W,0)+ISNULL(NKM_G,0)+ISNULL(NKM_B,0)+ISNULL(NKM_GA,0)+ISNULL(NKM_SP,0)+ISNULL(NKM_S,0) AS Nettokaltmiete
,obj.ObjektBezeichnung
FROM cashin c
LEFT JOIN dbo.TA0200_Objekt obj ON c.ObjektLFN=obj.ObjektLFN
WHERE DOMUS4000_MIRROR_1.dbo.cdIsValidImDatum(GETDATE(),3,obj.ObjektLFN)>0
) tbl1
PIVOT (
SUM(Nettokaltmiete)
FOR Jahr IN (' + #years4Pivot + N')
) pvt
ORDER BY ObjektBezeichnung ASC '
exec sp_executesql #query;
and the screenshots of execution plan:
Here is the link for a better looking :)
https://www.brentozar.com/pastetheplan/?id=HkSEjV7Av
Also the code for the function cdIsValidImDatum is here:
USE [DOMUS4000_MIRROR_1]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-------------------------------------------------------------------------------------------------------------------------------
ALTER FUNCTION [dbo].[cdIsValidImDatum](#bDate DATE, #bLevel int,#lfn int) RETURNS INT
AS
BEGIN
DECLARE #tmpInt INT
/*
#bLevel
1: Mandant
2: Kreis
3: Objekt
4: Einheit
*/
IF #bDate IS NULL OR #bLevel IS NULL OR #lfn IS NULL
BEGIN
SET #tmpInt = 0
END
ELSE
BEGIN
IF #bLevel = 4
BEGIN
SET #tmpInt =
(
SELECT
COUNT(*)
FROM
dbo.TA0310_MietEigEinheit AS einh LEFT JOIN
dbo.TA0200_Objekt AS obj ON einh.ObjektLFN = obj.ObjektLFN LEFT JOIN
dbo.TA0100_Kreis AS kre ON obj.KreisLFN = kre.KreisLFN LEFT JOIN
dbo.TA0010_Mandant AS man ON kre.MandantLFN = man.MandantLFN
WHERE
LEFT(ISNULL(man.MandantCode, ''), 1) <> '0'
AND
RIGHT(LEFT(ISNULL(man.MandantCode, ''), 3),1) <> '1'
AND
(man.MandantBeginn <= #bDate OR man.MandantBeginn IS NULL)
AND
(man.MandantEnde >= #bDate OR man.MandantEnde IS NULL)
AND
LEFT(ISNULL(kre.KreisCode, ''), 1) <> '0'
AND
RIGHT(LEFT(ISNULL(obj.ObjektCode, ''), 2),1) <> '0'
AND
(obj.ObjektVerwaltungsbeginn <= #bDate OR obj.ObjektVerwaltungsbeginn IS NULL)
AND
(obj.ObjektVerwaltungsende >= #bDate OR obj.ObjektVerwaltungsende IS NULL)
AND
(einh.GueltigBis >= #bDate OR einh.GueltigBis IS NULL)
AND
(einh.EinheitErstbezug <= #bDate OR einh.EinheitErstbezug IS NULL)
AND einh.EinheitLFN=#lfn
)
END
ELSE IF #bLevel = 3
BEGIN
SET #tmpInt =
(
SELECT
COUNT(*)
FROM
dbo.TA0200_Objekt AS obj LEFT JOIN
dbo.TA0100_Kreis AS kre ON obj.KreisLFN = kre.KreisLFN LEFT JOIN
dbo.TA0010_Mandant AS man ON kre.MandantLFN = man.MandantLFN
WHERE
LEFT(ISNULL(man.MandantCode, ''), 1) <> '0'
AND
RIGHT(LEFT(ISNULL(man.MandantCode, ''), 3),1) <> '1'
AND
(man.MandantBeginn <= #bDate OR man.MandantBeginn IS NULL)
AND
(man.MandantEnde >= #bDate OR man.MandantEnde IS NULL)
AND
LEFT(ISNULL(kre.KreisCode, ''), 1) <> '0'
AND
RIGHT(LEFT(ISNULL(obj.ObjektCode, ''), 2),1) <> '0'
AND
(obj.ObjektVerwaltungsbeginn <= #bDate OR obj.ObjektVerwaltungsbeginn IS NULL)
AND
(obj.ObjektVerwaltungsende >= #bDate OR obj.ObjektVerwaltungsende IS NULL)
AND
obj.ObjektLFN=#lfn
)
END
ELSE IF #bLevel = 2
BEGIN
SET #tmpInt =
(
SELECT
COUNT(*)
FROM
dbo.TA0100_Kreis AS kre INNER JOIN
dbo.TA0010_Mandant AS man ON kre.MandantLFN = man.MandantLFN
WHERE
LEFT(ISNULL(man.MandantCode, ''), 1) <> '0'
AND
RIGHT(LEFT(ISNULL(man.MandantCode, ''), 3),1) <> '1'
AND
(man.MandantBeginn <= #bDate OR man.MandantBeginn IS NULL)
AND
(man.MandantEnde >= #bDate OR man.MandantEnde IS NULL)
AND
LEFT(ISNULL(kre.KreisCode, ''), 1) <> '0'
AND
kre.KreisLFN=#lfn
)
END
ELSE IF #bLevel = 1
BEGIN
SET #tmpInt =
(
SELECT
COUNT(*)
FROM
dbo.TA0010_Mandant AS man
WHERE
LEFT(ISNULL(man.MandantCode, ''), 1) <> '0'
AND
RIGHT(LEFT(ISNULL(man.MandantCode, ''), 3),1) <> '1'
AND
(man.MandantBeginn <= #bDate OR man.MandantBeginn IS NULL)
AND
(man.MandantEnde >= #bDate OR man.MandantEnde IS NULL)
AND
man.MandantLFN=#lfn
)
END
END
RETURN #tmpInt
END
Finally guys I found the solution. I dropped it down to 4 seconds. I did
LEFT JOIN in this
LEFT JOIN dbo.TA0300_MietEig mieteig ON joupos.MietEigLFN = mieteig.MietEigLFN
and in the WHERE section I fielded with this:
WHERE
JournalArt = 21
AND pos.PositionArt=1
AND RIGHT(LEFT(mieteig.MietEigCode1,5),1) IS NOT NULL
AND RIGHT(LEFT(MietEigCode1,5),1) LIKE '' ''
The results were the same.
If anyone has more accurate answer please do not hesitate to explain in this post.
Thanks again.

Updating SQL Server based on unique row using WHILE LOOP

I'm trying to update my table using WHILE LOOP, unfortunately, instead of updating it based on employeeidno, it gathers all the total aremployee in all employeeidno and then update the row of all employeeidno based on it.
Is there a way to segregate the SET #aremployee based on employeeidno?
What I basically what for this query is that for every WHILE LOOP it will capture the data gathered, and then add it to the next loop, but is based on employeeidno.
DECLARE #cnt INT = 0;
DECLARE #aremployee FLOAT = 0;
WHILE #cnt <= (SELECT TOP 1 RIGHT(accountcode,2) FROM accounting_tblearningsamendmentaccount_db WHERE LEFT(accountcode,2) = '02' AND approvedby IS NOT NULL ORDER BY accountcode DESC)
BEGIN
SET #cnt = #cnt + 1;
UPDATE accounting_tblpayroll_db
SET #aremployee = #aremployee + x.aremployee,
accounting_tblpayroll_db.aremployee = #aremployee
FROM (SELECT
MAX(RTRIM(LTRIM(employeeidno))) AS 'employeeidno',
SUM(debit) AS 'aremployee',
MAX(accountcode) as 'accountcode',
MAX(RTRIM(LTRIM(referenceno))) AS 'referenceno',
MAX(RTRIM(LTRIM(particulars))) AS 'particulars',
MAX(RTRIM(LTRIM(postedby))) AS 'postedby',
MAX(RTRIM(LTRIM(approvedby))) AS 'approvedby',
MAX(RTRIM(LTRIM(notedby))) AS 'notedby'
FROM accounting_tblearningsamendment_db WHERE LEFT(accountcode,2) = LEFT('02000',2)
AND accountcode != '02001' AND accountcode != '02002'
AND payrolldue is null AND datedue BETWEEN '2020-10-06' AND '2020-10-20'
AND accountcode = CONCAT('020', CONCAT(CASE WHEN #cnt < 10 THEN '0' ELSE '' END , #cnt))
GROUP BY employeeidno) AS x
WHERE x.employeeidno = accounting_tblpayroll_db.employeeidno
AND x.aremployee <
(((accounting_tblpayroll_db.cutoffpay + accounting_tblpayroll_db.leave + accounting_tblpayroll_db.nightdifferential + accounting_tblpayroll_db.regularholiday + accounting_tblpayroll_db.specialholiday + accounting_tblpayroll_db.additionalincome + accounting_tblpayroll_db.overtime
+ accounting_tblpayroll_db.apemployee + accounting_tblpayroll_db.thmonth + accounting_tblpayroll_db.christmasbonus + accounting_tblpayroll_db.administrativeallowance + accounting_tblpayroll_db.supervisoryallowance
+ accounting_tblpayroll_db.hazardallowance + accounting_tblpayroll_db.shortageallowance + accounting_tblpayroll_db.licenseallowance + accounting_tblpayroll_db.transportationallowance + loyaltyincentiveallowance - '1000.00'
)
- (accounting_tblpayroll_db.sss_ee + accounting_tblpayroll_db.med_ee + accounting_tblpayroll_db.pagibig_ee + accounting_tblpayroll_db.late + accounting_tblpayroll_db.undertime)))
AND accounting_tblpayroll_db.datefrom = '2020-10-06'
AND accounting_tblpayroll_db.dateto = '2020-10-20';
END;
Thank you in advance.
Edit:
This is the simplified version:
DROP TABLE #temtable1;
DROP TABLE #temtable2;
CREATE TABLE #temtable1
(
referenceno int,
employeeid varchar(10),
ccode varchar(10),
amount float(10)
);
INSERT INTO #temtable1
(referenceno,employeeid,ccode,amount)
VALUES('1001','2001','3001','11000.00');
INSERT INTO #temtable1
(referenceno,employeeid,ccode,amount)
VALUES('1003','2002','3002','11000.00');
INSERT INTO #temtable1
(referenceno,employeeid,ccode,amount)
VALUES('1005','2003','3003','11000.00');
INSERT INTO #temtable1
(referenceno,employeeid,ccode,amount)
VALUES('1001','2001','3004','10000.00');
INSERT INTO #temtable1
(referenceno,employeeid,ccode,amount)
VALUES('1003','2002','3005','10000.00');
INSERT INTO #temtable1
(referenceno,employeeid,ccode,amount)
VALUES('1005','2003','3006','10000.00');
CREATE TABLE #temtable2
(
referenceno int,
employeeid varchar(10),
total float(10)
);
INSERT INTO #temtable2
(referenceno,employeeid,total)
VALUES('1001','2001',NULL);
INSERT INTO #temtable2
(referenceno,employeeid,total)
VALUES('1002','2002',NULL);
INSERT INTO #temtable2
(referenceno,employeeid,total)
VALUES('1003','2003',NULL);
DECLARE #cnt INT = 0;
DECLARE #total INT = 0;
WHILE #cnt <= 10
BEGIN
SET #cnt = #cnt + 1;
UPDATE #temtable2
SET #total = #total + x1.amount,
total = #total
FROM(SELECT
MAX(referenceno) as referenceno,
MAX(employeeid) as employeeid,
ccode as ccode,
SUM(amount) as amount
FROM #temtable1
WHERE
ccode = CONCAT('30', CONCAT(CASE WHEN #cnt < 10 THEN '0' ELSE '' END , #cnt))
GROUP BY
employeeid,ccode) AS x1
WHERE x1.employeeid = #temtable2.employeeid
AND x1.amount < 25000
END
select * from #temtable2
Current Result:
Expected Result:
What I intend for this is that the query will loop and add all code that starts with 3, depending on what employeeid the data is under.
The query will the first loop starting 3001, then up to 3010, and add it consecutively until it will not exceed 25000, but it's on every employeeid.

While Loop Issue

Hoping that someone can offer some assistance, I am currently working on a piece of code which seems to be having issues. Unfortunately I cant post the underlying data but will try and explain.
The code currently cycles through a selection of kpi's and calculates if something needs to be run or not based on the current time and whether the individual kpi's need to be run. At the moment if I hard code a number of kpi's the code works fine but if I let it cycle through all the kpi's, ones that should not run are being told to run, also in the select that defines things like #Period, when I let it run through all KPI's its setting the #Period incorrectly when it shouldn't run but when its meant to run it set it fine.
Overall I have 2 issues which I think are related KPI's run when they are not meant to and when they are running when they are not meant to they pick up the wrong Period either way which is odd. I think what is happening is when I let it run all the way through the KPI's are getting mixed up but I cant see how this is happening, any help would be great before I go mad.
As you can see from my code there are 2 #current_timestamps, when its set to 23.45.18.873 it should not run some of the kpi's but it runs them all anyway and the 21.45.18.873 means that they can run.
declare #job_current_time_minute float,
#job_current_date_time_minute as datetime,
#current_timestamp as datetime
SET #job_current_time_minute = 52--cast(datepart(minute, getdate()) as float)
SET #job_current_date_time_minute = getdate()
--SET #current_timestamp = cast('2017-04-02 23:45:18.873' as datetime)
SET #current_timestamp = cast('2017-04-02 21:45:18.873' as datetime)
--Run: 88 6 0 52 5 5 5
--Run: 88 1 10 52 5 5 5
declare
#kpi_id int,
#kpi_parent_id int,
#sql nvarchar(max),
#kpi_last_result nvarchar(100),
#kpi_last_runtime datetime,
#kpi_params nvarchar(max),
#kpi_current_time_minute float,
#schedulue_minute float,
#reoccurrence float,
#result float,
#kpi2 int,
-- Email Variables
#kpi_name nvarchar(150),
#kpi_desc nvarchar(150),
#kpi_report_link nvarchar(150),
#kpi_email_subject nvarchar(150),
#kpi_email_body nvarchar(300),
#kpi_email_query nvarchar(max),
#kpi_sms_msg nvarchar(300);
SET #kpi_params = N'#retvalOUT varchar(max) OUTPUT';
select #kpi_id = min(kpi_id) from KPI where KPI_Active = 1; --and kpi_id in (86, 88)
while #kpi_id is not null
begin
select
#kpi_parent_id = kpi_parent_id,
#sql = kpi_Script,
#schedulue_minute = datepart(minute,s.Schedule_Start),
#reoccurrence = s.Reoccurrence,
#result = cast((#job_current_time_minute - datepart(minute,s.Schedule_Start)) / s.Reoccurrence as decimal(18,2)),
#kpi_name = kpi_name,
#kpi_desc = kpi_desc,
#kpi_report_link = kpi_report_link,
#kpi_email_subject = kpi_email_subject,
#kpi_email_body = kpi_email_body,
#kpi_email_query = kpi_email_query,
#kpi_sms_msg = kpi_sms_msg,
#kpi_current_time_minute = 60*DATEPART(HOUR, GETDATE())+DATEPART(MINUTE,GETDATE()),
#kpi2 = KPI_ID
from EWI..KPI
inner join EWI..Schedule s on KPI.Schedule_ID = s.Schedule_ID where kpi_id = #kpi_id--order by kpi_id asc
--set #sql = 'select #retvalOUT= (' + #sql + ')'
if floor(#result) <> ceiling(#result)
begin
PRINT 'Not Time to Run: ' + ' ' + cast(#kpi_id as varchar(11)) + ' ' + cast(#result as varchar(11))
end
else
begin
declare
#ThresholdID int,
#PeriodID int,
#Threshold_value int,
#Threshold_PosNeg nvarchar(5)
select #ThresholdID = Threshold_ID, #PeriodID = Period_ID, #Threshold_value = Threshold_value, #Threshold_PosNeg = Threshold_PosNeg from (
-- select * from (
select * from (
select KPI_ID, t.Threshold_ID, p.Period_ID, t.Threshold_Value, t.Threshold_PosNeg, p.DayStartTime, p.DayEndTime, Period_desc, [Day]
from EWI..Threshold t join
EWI..Period p on t.Period_ID = p.Period_ID where KPI_ID = #kpi_id
) x where (case when [Day] = datename(dw,getdate()) then Period_id
when [Day] = choose(datepart(dw, getdate()), 'WEEKEND','Weekday','Weekday','Weekday','Weekday','Weekday','WEEKEND') then Period_ID
when [Day] = 'All' then Period_ID end) is not null
) y where case when datediff(second,DayStartTime,DayEndTime) > 0 then
case when convert(time(0), #current_timestamp) >= DayStartTime and convert(time(0), #current_timestamp) < DayEndTime then 1 else 0 end
else case when convert(time(0), #current_timestamp) >= DayStartTime or convert(time(0), #current_timestamp) < DayEndTime then 1 else 0 end
end = 1
select 'Run: ' + cast(#kpi_id as varchar(11)) + ' ' + cast(#PeriodID as varchar(11)) + ' ' +
cast(#Threshold_value as varchar(11)) + ' ' + cast(#job_current_time_minute as varchar(11)) + ' ' +
cast(#result as varchar(11)) + ' ' +
cast(ceiling(#result) as varchar(11))+ ' ' +cast(floor(#result) as varchar(11))
end
select #kpi_id = min(kpi_id) from KPI where KPI_Active = 1 and kpi_id > #kpi_id;
end
Take a look at this rextester demo. Do you agree that this model reproduces the problem? It seems that comparing ceiling(#result) to floor(#result) will indeed give everywhere true.
After our discussion it seems to me that the test should be:
if (#result - datepart(minute, Schedule_Start)) % #reoccurrence = 0
or something like that. But this assumes #reoccurence to be an integer.

MSSQL After Insert Trigger not executing after database restore

I restored a SQL 2k5 Database to a SQL 2014 server (Note this is a SQL Web Edition instance) and it does not seem to execute at all.
CREATE TRIGGER [dbo].[tInsertTransactionsSnapshot]
ON [GDL_TNA].[dbo].[TRANSACTIONS]
AFTER INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #FirstRecord int
DECLARE #LastRecord int
DECLARE #MSTSQ int
DECLARE #EventDate varchar(50)
SET #FirstRecord = (SELECT TOP 1 T_ID FROM INSERTED ORDER BY T_ID ASC)
SET #LastRecord = (SELECT TOP 1 T_ID FROM INSERTED ORDER BY T_ID DESC)
insert into GDL_TNA.dbo.dbg(Dbgfirst,dbgLast) VALUES (#FirstRecord,#LastRecord)
WHILE #FirstRecord <= #LastRecord
BEGIN
SET #MSTSQ = (SELECT MST_SQ FROM INSERTED WHERE T_ID = #FirstRecord)
SET #EventDate = (SELECT T_Date FROM INSERTED WHERE T_ID = #FirstRecord)
IF EXISTS(SELECT NULL FROM GDL_TNA.dbo.SNAPSHOTs WHERE MST_SQ = #MSTSQ AND SS_EVENT_DATE = #EventDate AND SS_ACTIVE = 1 AND SS_TYPE = 'TRANSACTION')
BEGIN
UPDATE GDL_TNA.dbo.SNAPSHOTs SET SS_ACTIVE = 0 WHERE MST_SQ = #MSTSQ AND SS_EVENT_DATE = #EventDate AND SS_ACTIVE = 1 AND SS_TYPE = 'TRANSACTION'
END
INSERT INTO GDL_TNA.dbo.SNAPSHOTs
(
[SS_TYPE]
,[SS_EVENT]
,[MST_SQ]
,[MD_ACTIVE]
,[MST_FIRST_NAME]
,[MST_LAST_NAME]
,[MD_SHIFTSTART]
,[MD_SHIFTEND]
,[COMP_ID]
,[DEPT_ID]
,[FUNC_ID]
,[MST_PREVIOUS_FIRST_NAME]
,[MST_PREVIOUS_LAST_NAME]
,[MST_RATE_NORMAL]
,[MST_RATE_TIMEANDHALF]
,[MST_RATE_DOUBLE]
,[MST_RATE_SPECIAL]
,[SS_EVENT_ID]
,[SS_EVENT_DATE]
,[SS_EVENT_START]
,[SS_EVENT_END]
,[SS_EVENT_APPROVED]
,[SS_EVENT_RATETYPE]
)
SELECT
'TRANSACTION'
,'INSERT'
,MST_SQ
,MD_ACTIVE
,MST_FIRST_NAME
,MST_LAST_NAME
,MD_SHIFTSTART
,MD_SHIFTEND
,COMP_ID
,DEPT_ID
,FUNC_ID
,MST_PREVIOUS_FIRST_NAME
,MST_PREVIOUS_LAST_NAME
,MST_RATE_NORMAL
,MST_RATE_TIMEANDHALF
,MST_RATE_DOUBLE
,MST_RATE_SPECIAL
,(
SELECT T_ID
FROM INSERTED
WHERE T_ID = #FirstRecord
)
,(
SELECT T_Date
FROM INSERTED
WHERE T_ID = #FirstRecord
)
,ISNULL((
SELECT
CASE
WHEN len(T_TIMEIN) = 6 THEN left(T_TIMEIN,2) + ':' + right(left(T_TIMEIN,4),2) + ':' + right(T_TIMEIN,2) + '.000'
WHEN len(T_TIMEIN) < 6 THEN '0'+left(T_TIMEIN,1) + ':' + right(left(T_TIMEIN,3),2) + ':' + right(T_TIMEIN,2) + '.000'
END
FROM INSERTED
WHERE T_ID = #FirstRecord
),'00:00:00.000')
,ISNULL((
SELECT
CASE
WHEN len(T_TIMEOUT) = 6 THEN left(T_TIMEOUT,2) + ':' + right(left(T_TIMEOUT,4),2) + ':' + right(T_TIMEOUT,2) + '.000'
WHEN len(T_TIMEOUT) < 6 THEN '0'+left(T_TIMEOUT,1) + ':' + right(left(T_TIMEOUT,3),2) + ':' + right(T_TIMEOUT,2) + '.000'
END
FROM INSERTED
WHERE T_ID = #FirstRecord
),'00:00:00.000')
,1
,1
FROM GDL_TNA.dbo.MASTER_DETAILS
WHERE MST_SQ = #MSTSQ
SET #FirstRecord = #FirstRecord + 1
END
END
Steps I have Taken
Check Trigger Status: SELECT name, is_disabled FROM sys.triggers (All Enabled)
Drop & Recreate Triggers on 2014 instance
Ran a Recompile of table with sp_recompile
Any advice would be greatly appreciated.

how to show standard timing format result in sql server

I have a function like this:
ALTER FUNCTION [dbo].[podiumsummerytime] (#dec NUMERIC(18, 2)) RETURNS Varchar(50)
AS
BEGIN
DECLARE
#hour decimal(18,2),
#Mns decimal(18,2)
DECLARE #Average Varchar(50)
select #hour=CONVERT(int,#dec/60/60)
SELECT #Mns = convert(int, (#dec / 60) - (#hour * 60 ));
SELECT #Average = (case when #hour = 0 then ''
when #hour < 10 then '0' + cast(#hour as varchar(255)) + 'hr:'
else cast(#hour as varchar(255)) + 'hr:'
end) +
(case when #mns < 10 then '0' + cast(#mns as varchar(255)) + 'Mn:'
else cast(#mns as varchar(255))+ 'Mn'
end)
RETURN #Average
END
and i have a query like this:
select dbo.podiumsummerytime(
convert(decimal(10,1),
avg(convert(numeric(18,2), datediff(ss, t.dtime, t.PAICdate ))))
) as Avgparkingtime,
my result is getting like this:
Avgparkingtime
02.00hr:20.00min
if we have 1 hour now showing 1,instead of this i have to show 01.and if have 5 minutes showing 5,instead of that i have to show 05
so my expected out put like this:
Avgparkingtime
01hr:20Mn
any help is very appreciable
It seems like you want to zero pad numbers. Because of the range, this is probably most easily done with case:
SELECT #Average = (case when #hour = 0 then ''
when #hour < 10 then '0' + cast(#hour as varchar(255)) + 'hr:'
else cast(#hour as varchar(255)) + 'hr:'
end) +
(case when #min < 10 then '0' + cast(#mns as varchar(255)) + 'Mn:'
else cast(#mns as varchar(255) + 'Mn'
end) /* +
(case when #second < 10 then '0' + cast(#second as varchar(255))
else cast(#second as varchar(255))
end) */;
However, I think you should just use the format "HH:MM:SS". This is a standard format, easily understandable, and can be generated using convert().