SQL Server trigger - works on UPDATE but not on INSERT - sql-server

The following trigger (which updates a column in the same table as the insert or update) works perfectly for UPDATEs, but doesn't seem to fire for INSERTs. Is it possible to run an update on?
What am I missing?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[OnEvaluationCreateOrEdit]
ON [dbo].[tblEvaluationFormResultsSummary]
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
-- get the last id value of the record inserted or updated
DECLARE #id BIGINT;
SELECT #id = EvaluationFormResultSummaryID
FROM INSERTED;
-- Insert statements for trigger here
UPDATE A
SET A.Outcome = CASE
WHEN B.[# of fail alls] > 0 THEN 'Poor'
WHEN B.[# of Fail Amber] / [# of Live Questions] >= 0.3 THEN 'Poor'
WHEN B.[# of Fail Amber] > 0 THEN 'Development Needed'
WHEN B.[# of Fail Green] / [# of Live Questions] >= 0.4 THEN 'Development Needed'
WHEN B.[# of Fail Green] > 0 THEN 'Right First Time - Coaching Required'
ELSE 'Right First Time'
END
FROM
dbo.tblEvaluationFormResultsSummary AS A
INNER JOIN
(SELECT
SUM(CASE WHEN FormQuestionRatingOptionFailAll = 1 THEN 1 ELSE 0 END) as [# of fail alls],
SUM(CASE WHEN FormQuestionRatingOptionIsNA = 1 THEN 1 ELSE 0 END) as [# of N/A],
SUM(CASE WHEN FormQuestionRatingOptionLabel = 'Fail / Amber' THEN 1 ELSE 0 END) as [# of Fail Amber],
COUNT(EFRS.EvaluationFormResultsSummaryID) as [No of Questions],
COUNT(EFRS.EvaluationFormResultsSummaryID) - SUM(CASE WHEN FormQuestionRatingOptionIsNA = 1 THEN 1 ELSE 0 END) as [# of Live Questions],
SUM(CASE WHEN FormQuestionRatingOptionLabel = 'Fail / Green' THEN 1 ELSE 0 END) AS [# of Fail Green],
EFRS.EvaluationFormResultsSummaryID
FROM
dbo.tblEvaluationFormResultsDetails AS EFRS
INNER JOIN
dbo.tblEvaluationFormQuestionRatingOptions AS RO ON EFRS.QuestionRatingOptionID = RO.FormQuestionRatingOptionID
WHERE
(EFRS.EvaluationFormResultsSummaryID = #id)
GROUP BY
EFRS.EvaluationFormResultsSummaryID) B ON a.EvaluationFormResultSummaryID = B.EvaluationFormResultsSummaryID
WHERE
A.EvaluationFormResultSummaryID = #id
END
Thanks in advance!

Related

need help for select function in sql

In a table I have 914 rows in that I have a Column which contains "yes or no" values(Yes=193 No = 721 total 914).
In this I want to create a function to use in select statement How many Yes and No
I wrote a query
create function TSS(
#string as nvarchar(20)
)
returns int
begin
declare #result int
if (#string='NO')
select #result=sum(case Re_engaged when 'NO' then 1 else null end) from TVS_PRE
else if (#string='YES')
select #result=sum(case Re_engaged when 'YES' then 1 else null end) from TVS_PRE
return #result
end
select [dbo].[TSS]('Yes') as columns_with_Yes,[dbo].[TSS]('No') as columns_with_No from TVS_PRE
And I got the result is
Columns_with_Yes
Columns_with_No
1
193
2
193
3
193
upto...
...
914
193
but I required this
Columns_with_Yes
Columns_with_No
1
193
You should combine this into one query
SELECT
sum(case Re_engaged when 'NO' then 1 end) Columns_with_No,
sum(case Re_engaged when 'YES' then 1 end) Columns_with_Yes
FROM TVS_PRE;
If you really want this as a function, you can turn it into an inline Table valued Function
CREATE FUNCTION TSS()
RETURNS TABLE
AS RETURN (
SELECT
sum(case Re_engaged when 'NO' then 1 end) Columns_with_No,
sum(case Re_engaged when 'YES' then 1 end) Columns_with_Yes
FROM TVS_PRE
);
GO
I don't understand your need... but if you want only one row... then dont use "from":
select [dbo].[TSS]('Yes') as columns_with_Yes,[dbo].[TSS]('No') as columns_with_No
Use this syntax
SELECT DISTINCT COUNT(CASE WHEN Re_engaged='No' then 1 else NULL end) OVER () AS No_col,
COUNT(CASE WHEN Re_engaged='Yes' then 1 else NULL end) OVER () AS Yes_col
FROM TVS_PRE

SQL Server 2012 : how do I join 2 case when clauses into 1 column?

I need some assistance with a query. I have a table with the following info:
enter image description here
I need to allocate a point system for every call, calls less than 1 min, calls between 1 and 5 min , calls between 5 and 10 min and lastly calls over 10 min
Currently my query looks like this:
Select distinct convert (date,AIV.PSEndTime,102) as TRXDATE
,AIV.Username
,AIV.FirstName+' '+AIV.LastName as Agent_Name
,AIV.ITypeDisplayValue
,convert (datetime,AIV.PSBeginTime,120) as PSBeginTime
,convert (datetime,AIV.PSEndTime,120) as PSEndTime
,convert(CHAR(8),DATEADD(second,AIV.Talking,0),108) as [Talking]
,CASE WHEN AIV.Talking <='60' THEN 1 ELSE 0 end as Less_than_1min
,CASE WHEN AIV.Talking between '61' and '300' THEN 1 ELSE 0 end as Between_1_and_5_min
,CASE WHEN AIV.Talking between '301' and '600' THEN 1 ELSE 0 end as Between_5_and_10_min
,CASE WHEN AIV.Talking >='601' THEN 1 ELSE 0 END as More_than_10min
From AgentInteractionsView as AIV WITH (NOLOCK)
WHere UserName in ('TomE','MicDe','JulCa')
and AIV.PSBeginTime > '2017-08-01'
and AIV.PSEndTime < '2017-09-01'
group by
convert (date,AIV.PSEndTime,102)
,AIV.Username
,AIV.FirstName+' '+AIV.LastName
,AIV.ITypeDisplayValue,AIV.DIDisplayValue
,convert (datetime,(DATEADD(hour,2,AIV.PSBeginTime)),120)
,convert (datetime,(DATEADD(hour,2,AIV.PSEndTime)),120)
,convert(CHAR(8),DATEADD(second,AIV.Talking,0),108)
,AIV.Talking
And this actually worked however I noticed that when the Column "talking" was Null it would not give me a result so I added a new query:
,CASE WHEN AIV.Talking <='60' THEN 1 ELSE 0 end as Less_than_1min
,CASE WHEN AIV.Talking = null THEN 1 ELSE 0 end as Less_than_1min
Hoping that these would result in a single column, but of course it gave me 2 columns with the same heading.
I want to join these two queries into 1 column, for example
,CASE WHEN AIV.Talking = null THEN 1
ELSE (CASE WHEN AIV.Talking <='60' THEN 1 ELSE 0) end
as Less_than_1min
am I missing something ( obviously) or am I expecting too much from SQL :)
As I mentioned in my comment, you can use ISNULL or COALESCE to handle a NULL value, example code:
DECLARE #time TIME;
SET #time = NULL;
SELECT CASE WHEN COALESCE(#time,'00:00:01') <= '00:01:00' THEN 1 ELSE 0 END AS Test_Time;
The above code returns a 1, as does:
DECLARE #time TIME;
SET #time = '00:00:01';
SELECT CASE WHEN COALESCE(#time,'00:00:01') <= '00:01:00' THEN 1 ELSE 0 END AS Test_Time;
And the below returns a 0:
DECLARE #time TIME;
SET #time = '00:02:01';
SELECT CASE WHEN COALESCE(#time,'00:00:01') <= '00:01:00' THEN 1 ELSE 0 END AS Test_Time;
As does:
DECLARE #time TIME;
SET #time = NULL;
SELECT CASE WHEN #time <= '00:01:00' THEN 1 ELSE 0 END AS Test_Time;
As the value is NULL, it cannot evaluate, so returns false.
So when using COALESCE, I just make sure that what I set the value to be if it is NULL fits in with the CASE expression logic, to return what I require.
Thanks for the assistance I was able to figure out what I was doing wrong.
As the Time is and Integer Showing the number of Seconds I came to this solution :)
Select CASE WHEN AIV.Talking <='60' THEN 1 ELSE 0 end as Less_than_1min
,CASE WHEN AIV.Talking between '61' and '300' THEN 1 ELSE 0 end as Between_1_and_5_min ,
CASE WHEN AIV.Talking between '301' and '600' THEN 1 ELSE 0 end as Between_5_and_10_min
,CASE WHEN AIV.Talking >='601' THEN 1 ELSE 0 END as More_than_10min
I really hope that this helps someone else in future :)

I need to write proc which give me report of all my Student, the Male and Female but per different Country?

I have data for my Student in my lookupdata table (Enrolled, Droped Out, Canclled, all with ldTypeID = 129). The rest of my data is stored in vStudent. I need to write proc which will give me a report of all my Student, the Male and Female but per different Country. Where did I go wrong with my code?
Student Status Total Number Total # Males Total # Females
Enrolled
Dropped Out
Cancelled
Graduated
CREATE PROCEDURE [dbo].[pr_ReportPerCountry]
#CountryID int
AS
DELETE FROM ReportData WHERE rdTypeID = 2
INSERT INTO ReportData
(
rdSortBy,
rdTypeID,
rdName1,
rdValue1,
rdValue2,
rdValue3,
)
Select
0 AS SoryBy,
2 AS rdTypeID,
finalStudentStatus,
sum (case when peFinalStatusID in (303) then 1 else 0 end) as TotalEnrolled,
sum(case when (peFinalStatusID in (303) and peSexID=7) then 1 else 0 end) as MaleEnrolled,
sum(case when (peFinalStatusID in (303) and peSexID=8) then 1 else 0 end) as FemaleEnrolled
from vStudentPerson
left join (SELECT ldLookupDataID,ldValue FROM LookupData
WHERE ldTypeID = 129
group by ldLookupDataID,ldValue
) sta on peFinalStatusID=sta.ldLookupDataID
WHERE peFinalStatusID in (297,298,299,303) and peCountryofResidencyID = 0 or peCountryofResidencyID=#CountryID
I find solution, thanks anyway.
INSERT INTO ReportData
(
rdSortBy,
rdTypeID,
rdName1,
rdValue1,
rdValue2,
rdValue3
)
Select
0 AS SoryBy,
1 AS rdTypeID,
academicYear,
count (pePersonID) as TotalAwarded,
sum (case when peSexID = 7 then 1 else 0 end ) as TotalAwardedMale,
sum (case when peSexID = 8 then 1 else 0 end ) as TotalAwardedFemale
from vStudentPerson
left join (SELECT * FROM vStudentPersonScholarship) sch on pePersonID=sch.psPersonID
where (#CountryID = -1 or peCountryofResidencyID = #CountryID) and psScholarahipRenewalsTypeID=281
group by sch.academicYear

Stored Procedure Summation Of rows with same ID

I have stored procedure in which I get Data In between the desired months from user.
Q1. I want to show Membername instead of memberID. How do i get member name here from the member master table?
Q2. Secondly I want to add these rows(summation). Like each row stores a int value. I want the same rows with same member ID to add up and show me one single row for each type.
for example if there are three entries for visitors in 3 months I dont want three separate rows display 1,1,1 instead I want a single row with value 3
USE [MTS]
GO
/****** Object: StoredProcedure [dbo].[sp_MTS_MemberTracking_generateReport] Script Date: 07-04-2015 14:48:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- sp_MTS_MemberTracking_generateReport '01/01/2015','03/01/2015'
-- =============================================
ALTER PROCEDURE [dbo].[sp_MTS_MemberTracking_generateReport]
-- Add the parameters for the stored procedure here
#monthYearFrom datetime , #monthYearTo datetime
AS
select MemberId,TrackingId,MonthYear, AttendanceInFormalMixer,AttendanceInFbb,GoodKarmaCredit,CupOfCofee,Business,Training,Visitors
from [dbo].[MTS_MemberTracking] MtsTracking
where MtsTracking.MonthYear >= #monthYearFrom and MtsTracking.MonthYear <= #monthYearTo
After looking through your code and web page. you need something like this.
ALTER PROCEDURE [dbo].[sp_MTS_MemberTracking_generateReport]
-- Add the parameters for the stored procedure here
#monthYearFrom datetime , #monthYearTo datetime
AS
select max(mtsmem.Name) Name,MtsTracking.MemberId,--TrackingId,MonthYear,
sum(Convert(int,AttendanceInFormalMixer))*10 AttendanceInFormalMixer,
sum(Convert(int,AttendanceInFbb))*10 AttendanceInFbb,
sum(CASE WHEN GoodKarmaCredit <> 0 THEN 10 ELSE 0 END) GoodKarmaCredit,
sum(CASE WHEN CupOfCofee <2 THEN CupOfCofee*5 ELSE 10 END) CupOfCofee,
sum(CASE WHEN Convert(int,Business)<>0 THEN 10 ELSE 0 END) Business,
sum(CASE WHEN Training<>0 THEN 10 ELSE 0 END) Training,
sum(CASE WHEN Visitors<>0 THEN 10 ELSE 0 END) Visitors,
convert(decimal(10,2),(sum(Convert(int,AttendanceInFormalMixer))*10 +
sum(Convert(int,AttendanceInFbb))*10 +
sum(CASE WHEN GoodKarmaCredit <> 0 THEN 10 ELSE 0 END) +
sum(CASE WHEN CupOfCofee <2 THEN CupOfCofee*5 ELSE 10 END) +
sum(CASE WHEN Convert(int,Business)<>0 THEN 10 ELSE 0 END) +
sum(CASE WHEN Training<>0 THEN 10 ELSE 0 END) +
sum(CASE WHEN Visitors<>0 THEN 10 ELSE 0 END) )*1.00/7)
UserScore
from [dbo].[MTS_MemberTracking] MtsTracking
inner join MTS_Members mtsmem on MtsTracking.MemberId = mtsmem.MemberId
where MtsTracking.MonthYear >= #monthYearFrom and MtsTracking.MonthYear <= #monthYearTo
group by MtsTracking.MemberId

SQL Server - need assistance with sum and case statements

I'm using SQL Server 2005. I'm looking to add up the columns (AM, Midday, Evening) to see which ones contains the value "YES" and then take that total and multiply it by the rate for each row for a client.
Here is the query I have so far:
Select
Sum(Case When morning = 'yes' Then 1 Else 0 End) am_total,
Sum(Case When midday = 'yes' Then 1 Else 0 End) midday_total
From services
where client_id = 24
with the following output
am_total midday_total
45 49
When I introduce the rate variable, my query starts telling me I need the group_by clause and I don't think I'm ready for that since I still need to add the am_total and the midday_total together first and then multiply that by the rate.
Ultimately, all I'm looking for is the grand total.
If I understand your question, maybe this is what you need
declare #rate int
set #rate = 2 /*what ever rate is */
select am_total * #rate as am, midday_total * #rate as midday
from (
Select
Sum(Case When morning = 'yes' Then 1 Else 0 End) am_total,
Sum(Case When midday = 'yes' Then 1 Else 0 End) midday_total
From services
where client_id = 24
)
You can also join another table and use its columns in calculation
Select
Sum(Case When morning = 'yes' Then 1 * u.rate Else 0 End) am_total,
Sum(Case When midday = 'yes' Then 1 * u.rate Else 0 End) midday_total
From services srv inner join users u on services.id = u.service_id -- assuming this is relation
pay attention on u.rate above

Resources