sql trigger - restrict by time - sql-server

I want this trigger to work only between a certain time and another time (say 6am-10pm). please help!
ALTER TRIGGER [db].[el] ON [Reports].[db].[stat]
AFTER INSERT, UPDATE
AS
SET NOCOUNT ON;
INSERT INTO [Reports].[db].[el]
(
[StationID]
,[Count]
)
SELECT i.StationID,
i.[EmptyDockCount],
GETDATE(),
NULL,
NULL,
i.[LastUpdateDate],
FROM INSERTED i
INNER JOIN DELETED d
on d.StationID = i.StationID
INNER JOIN DBOS.dbo.StationDim bsd
ON bsd.StationID = i.StationID
WHERE i.[Count] = 0
AND d.[count] <> 0
;

Try like this,
This is the key statement CONVERT(TIME, Getdate()) BETWEEN '6:00:00.0000000' AND '22:00:00.0000000'
ALTER TRIGGER [db].[el]
ON [Reports].[db].[stat]
AFTER INSERT, UPDATE
AS
SET NOCOUNT ON;
IF CONVERT(TIME, Getdate()) BETWEEN '6:00:00.0000000' AND '22:00:00.0000000'
BEGIN
INSERT INTO [Reports].[db].[el]
([StationID],
[Count])
SELECT i.StationID,
i.[EmptyDockCount],
Getdate(),
NULL,
NULL,
i.[LastUpdateDate]
FROM INSERTED i
INNER JOIN DELETED d
ON d.StationID = i.StationID
INNER JOIN DBOS.dbo.StationDim bsd
ON bsd.StationID = i.StationID
WHERE i.[Count] = 0
AND d.[count] <> 0
END;

Related

SQL Server trigger only if a field is false prior to update

I have written the trigger below that inserts values if the emailstudio column is updated. This column can be 0 or 1.
How can I write the trigger so that it only fires if the emailstudio column is changed from 0 to 1, not if it was already 1?
Thank you
ALTER TRIGGER [dbo].[RM_Est_Email_Trigger]
ON [dbo].[K3_BriefHeader]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
DECLARE #estimate int, #Email_Date datetime, #status int, #emailstudio bit
SET #estimate = (SELECT Estimate from inserted)
set #Email_Date = GETDATE()
SET #status = (SELECT Status from inserted)
SET #emailstudio = (SELECT EmailStudio from inserted)
IF UPDATE (EmailStudio)
BEGIN
INSERT INTO [dbo].[K3_EstimateEmailDate] ([Estimate], [Email_Date],[Status], [EmailStudio])
VALUES (#estimate, #Email_Date, #status, #emailstudio)
END
END
Insert INTO [dbo].[K3_EstimateEmailDate] (
[Estimate]
,[Email_Date]
,[Status]
,[EmailStudio]
)
SELECT Estimate
,GETDATE()
,status
,1
FROM inserted
LEFT JOIN deleted
ON deleted.<primarykey> = inserted.<primarykey>
WHERE inserted.emailstudio = 1
AND (deleted.emailstudio is null -- inserted
OR deleted.emailstudio = 0) -- updated

SQL Server trigger compare inserted event date to existings records date

I have a SQL Server trigger I am working on and can't seem to get the inserted date to compare against a date column I have setup in another table. Here is the trigger I am working on:
CREATE TRIGGER TRIGNAME
ON TABLE
FOR INSERT
AS
BEGIN
DECLARE #REC INT
SELECT #REC = COUNT(*)
FROM INSERTED I
WHERE I.ID IS NOT NULL
AND I.COL2 = 'TEST'
IF (#REC > 0)
BEGIN
SELECT #REC = COUNT(*)
FROM INSERTED I
WHERE I.DATE > (SELECT DISTINCT S.DATE FROM TABLE1 S
WHERE I.PARENT_ID = S.PARENT_ID)
IF (#REC > 0)
BEGIN
UPDATE STATEMENT HERE
END
END
Not sure where I am going wrong here but the date column from Table1 is the same for the group of records with the same parent id.
Try declaring a DATETIME variable to store the Table1.Date value.
Then do the compare. And it might be just me but I like to use the inserted table by all lowercase letters.
CREATE TRIGGER TRIGNAME
ON TABLE
FOR INSERT
AS
BEGIN
DECLARE #REC INT
DECLARE #MyDate DateTime
SET #MyDate = (SELECT DISTINCT S.DATE FROM TABLE1 S
INNER JOIN inserted ON inserted.PARENT_ID = S.PARENT_ID)
SELECT #REC = COUNT(*)
FROM INSERTED I
WHERE I.ID IS NOT NULL
AND I.COL2 = 'TEST'
IF (#REC > 0)
BEGIN
SELECT #REC = COUNT(*)
FROM INSERTED I
WHERE I.DATE > #MyDate
IF (#REC > 0)
BEGIN
UPDATE STATEMENT HERE
END
END

SQL Trigger not updating all inserted rows

SQL Trigger is not updating all the inserted rows, only few rows get updated,I am not able to understand why. The rows are are getting row ID and RateID, I have tested the trigger by making rowId entries in the Audit log
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[mytrigger]
ON [dbo].[myTable]
AFTER INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #RowId int,
#RateID int,
#RateCode NVARCHAR(50)
SELECT #RateID = RateID,
#RowId = RowId
FROM inserted
// Method I found on StackOverflow
-- Update cr
-- Set cr.RateCode = r.RateCode
-- From mytable cr
-- inner join inserted on cr.RowId = inserted.RowId
-- inner join rates r on inserted.RateID = r.ID
--where cr.RowId = inserted.RowId
//Method Aaron Suggested
--UPDATE t1
--SET t1.RateCode = t2.RateCode
--FROM dbo.mytable AS t1
-- INNER JOIN dbo.rates AS t2
-- ON t1.RateID = t2.ID
-- WHERE t1.RowId = inserted.RowId
// Method I am currently using
IF #RateID IS NOT NULL
BEGIN
Select #RateCode = RateCode From rates where ID = #RateID
IF #RateCode IS NOT NULL
Update mytable Set RateCode = #RateCode Where RowId = #RowId
--UPDATE [dbo].[mytable ] SET RateCode = #RateCode FROM Inserted i WHERE mytable .RowId = i.RowId
END
END

Update trigger working but unable to do Insert

I have created a trigger which handles updates, and works well. But I am battling to work out how to handle Inserts.
This is my current trigger:
CREATE TRIGGER tr_PersonInCareSupportNeeds_History
ON PersonInCareSupportNeeds
FOR UPDATE
AS
BEGIN
INSERT INTO [dbo].[PersonInCareSupportNeeds_History]
([PersonInCareSupportNeedsID], [EventDate], [EventUser], [ChangedColumn], [PreviousValue], [NewValue])
SELECT i.[PersonInCareSupportNeedsID], GETDATE(), i.[LastUpdateUser], 'StartDate', CAST(d.[StartDate] AS VARCHAR), CAST(i.[StartDate] AS VARCHAR)
FROM PersonInCareSupportNeeds I INNER JOIN Deleted D
ON d.PersonInCareSupportNeedsID = I.PersonInCareSupportNeedsID
WHERE d.[StartDate] <> i.[StartDate]
UNION
-- new values
SELECT i.[PersonInCareSupportNeedsID], GETDATE(), i.[LastUpdateUser], 'EndDate', CAST(d.[EndDate] AS VARCHAR), CAST(i.[EndDate] AS VARCHAR)
FROM PersonInCareSupportNeeds I INNER JOIN DELETED D
ON d.PersonInCareSupportNeedsID = I.PersonInCareSupportNeedsID
WHERE d.[EndDate] <> i.[EndDate]
END
How can I change this to handle INSERTS as well. I will also hadd a column to handle the action type 'Updated' or 'Inserted'.
Funny, but I just happened to be playing with this:
create trigger dbo.Things_Log on dbo.Things after Delete, Insert, Update as
declare #Now as DateTimeOffset = SysDateTimeOffset();
-- Determine the action that fired the trigger.
declare #Action VarChar(6) =
case
when exists ( select 42 from inserted ) and exists ( select 42 from deleted ) then 'update'
when exists ( select 42 from inserted ) then 'insert'
when exists ( select 42 from deleted ) then 'delete'
else NULL end;
if #Action is NULL
return;
-- Assign a unique value to group the log rows for this trigger firing.
declare #TriggerId as Int;
update TriggerIds
set #TriggerId = TriggerId += 1;
-- Log the data.
if #Action in ( 'delete', 'update' )
insert into ThingsLog
select #Action + '-deleted', #TriggerId, #Now, dbo.OriginalLoginName(), ThingId, ThingName
from deleted;
if #Action in ( 'insert', 'update' )
insert into ThingsLog
select #Action + '-inserted', #TriggerId, #Now, dbo.OriginalLoginName(), ThingId, ThingName
from inserted;
go
-- Logging triggers should always fire last.
execute sp_settriggerorder #triggername = 'dbo.Things_Log', #order = 'Last', #stmttype = 'DELETE';
execute sp_settriggerorder #triggername = 'dbo.Things_Log', #order = 'Last', #stmttype = 'INSERT';
execute sp_settriggerorder #triggername = 'dbo.Things_Log', #order = 'Last', #stmttype = 'UPDATE';
go
The context:
create function [dbo].[OriginalLoginName]()
returns NVarChar(128)
as
begin
-- Returns the original login used to create the current session: Domain\username or sqlusername.
-- This function is not affected by impersonation.
-- Requires granting execute access to [public] and represents a diminutive security hole.
declare #Result as NVarChar(128);
select #Result = original_login_name
from sys.dm_exec_sessions
where session_id = ##SPID;
return #Result;
end;
go
CREATE TABLE [dbo].[Things](
[ThingId] [int] IDENTITY(1,1) NOT NULL,
[ThingName] [varchar](16) NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[ThingsLog](
[ThingsLogId] [int] IDENTITY(1,1) NOT NULL,
[Action] [varchar](16) NOT NULL,
[TriggerId] [int] NOT NULL,
[TriggerTime] [datetimeoffset](7) NOT NULL,
[OriginalLoginName] [nvarchar](128) NOT NULL,
[ThingId] [int] NOT NULL,
[ThingName] [varchar](16) NOT NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[TriggerIds](
[TriggerId] [int] NULL
) ON [PRIMARY]
GO
insert into dbo.TriggerIds ( TriggerId ) values ( 0 );
Logging triggers should be configured to fire last. This prevents logging actions that may be subsequently rolled back by other triggers. For bonus points, a query that can report logging triggers that are not configured to fire last (assuming you have a consistent naming convention, e.g. TableName_Log, for the triggers):
select PO.name as TableName, O.name as TriggerName, TE.type_desc,
case when O.name like PO.name + '_Log%' then 1 else 0 end as LoggingTrigger,
case when O.name like PO.name + '_Log%' and TE.is_last = 0 then 1 else 0 end as Misconfigured,
'' as [-], PO.type_desc as TableType, T.is_disabled, TE.is_first, TE.is_last, T.is_instead_of_trigger
from sys.objects as O inner join
sys.triggers as T on T.object_id = O.object_id inner join
sys.objects as PO on PO.object_id = T.parent_id inner join
sys.trigger_events as TE on TE.object_id = T.object_id
where
PO.type = 'U' and -- User table.
T.parent_class = 1 and -- Object or column trigger.
T.is_disabled = 0 and -- Is not disabled.
T.is_instead_of_trigger = 0 -- AFTER, not INSTEAD OF, trigger.
order by PO.name, O.name, TE.type_desc;
It can be incorporated in a stored procedure that corrects the firing order of logging triggers.

Sql Server error [SQLState 42000] (Error 325)

I have a script that utilizes the new Merge Output clause. I've run it in 3 different instances (all non-Production environments) and it works great. When I tried running it in our production environment, I get the error:
Executed as user: xxx\xxx. Incorrect syntax near 'Merge'. You
may need to set the compatibility level of the current database to a
higher value to enable this feature. See help for the SET
COMPATIBILITY_LEVEL option of ALTER DATABASE. [SQLSTATE 42000] (Error
325) Incorrect syntax near 'Merge'. You may need to set the
compatibility level of the current database to a higher value to
enable this feature. See help for the SET COMPATIBILITY_LEVEL option
of ALTER DATABASE. [SQLSTATE 42000] (Error 325). The step failed.
I've checked the versions of each instance and they are all 10.0.4000.0. All of the non-system databases are set to compatibility level 90 (2005), and system databases are set to 100 (2008). What else do I need to check to see where my production instance is different from the other non-Production instances?
Here's the query:
Declare #user varchar(20),
#message varchar(max)
Set #user = 'ISS20120917-144'
Create Table #data
(
CustomerEventID_Surrogate Int Identity (1,1) Not Null Primary Key,
CustomerNumber Int Not Null,
ConvictionEventID Int Not Null,
CustomerEventHierarchyID Int Not Null,
SanctionEventID Int Not Null,
ReferenceNumber varchar(40) Null,
ConvictionACDID Int Null,
State_Code varchar(2) Not Null,
County_ID Int Null,
CitationCDLHolderValueID Int Null,
Hazmat Bit Null,
CMV Bit Null,
PassengerEndorsement Bit Null,
OccurrenceDate DateTime Not Null,
ConvictionDate DateTime Not Null,
CourtOrder Bit Null
)
Create Table #surrogatemap
(
CustomerEventID_Surrogate Int Not Null,
NewCustomerEventID Int Not Null
)
Create Table #surrogateHIDmap
(
NewCustomerEventID Int Not Null,
NewHistoryEventDetailID Int Not Null
)
Begin Tran
Begin Try
Insert Into #data
Select ce.Cust_No,
ce.CustomerEventID,
ceh.CustomerEventHierarchyID,
ceSAN.CustomerEventID,
ce.ReferenceNumber,
hed.ACDID,
hed.State_Code,
hed.County_ID,
hed.CitationCDLHolderValueID,
hed.Hazmat,
hed.CMV,
hed.PassengerEndorsement,
hed.OccurrenceDate,
Case When cd.ConvictionDate IS NOT NULL Then cd.ConvictionDate
Else hed.OccurrenceDate
End As [ConvictionDate],
hed.CourtOrder
From IADS..CustomerEvent ce
Inner Join IADS..HistoryEventDetail hed On hed.CustomerEventID = ce.CustomerEventID
And hed.EndDate IS NULL
Inner Join IADS..CustomerEventCode cec On cec.CustomerEventCodeID = hed.CustomerEventCodeID
And cec.CustomerEventCodeID <> -51
Left Outer Join IADS..ConvictionDetail cd On cd.HistoryEventDetailID = hed.HistoryEventDetailID
Inner Join IADS..CustomerEventHierarchy ceh On ceh.CustomerEventID = ce.CustomerEventID
And ceh.EndDate IS NULL
Inner Join IADS..CustomerEvent ceSAN On ceSAN.CustomerEventID = ceh.RelatedCustomerEventID
And ceSAN.CustomerEventDispositionID IS NULL
Inner Join IADS..CustomerSanctionDetail csd On csd.CustomerEventID = ceSAN.CustomerEventID
And csd.SanctionDiscardedReasonID IS NULL
Inner Join IADS..SanctionReasonCode src On src.SanctionReasonCodeID = csd.SanctionReasonCodeID
And src.SanctionReasonCodeID = -320
Where ce.CustomerEventDispositionID IS NULL
Merge Into IADS..CustomerEvent
Using #data As src On 1 = 0
When Not Matched Then
Insert
(
CustomerEventCategoryID,
Cust_No,
ReferenceNumber,
CreatedBy,
CreatedDate,
UpdatedBy,
UpdatedDate
)
Values
(
-2,
src.CustomerNumber,
src.ReferenceNumber,
#user,
GetDate(),
#user,
GetDate()
)
Output
src.CustomerEventID_Surrogate,
inserted.CustomerEventID
Into #surrogatemap;
Select sm.NewCustomerEventID,
-8 As [HistoryEventTypeID],
-51 As [CustomerEventCodeID],
131 As [ACDID],
d.State_Code,
d.County_ID,
d.CitationCDLHolderValueID,
d.OccurrenceDate,
d.ConvictionDate,
d.Hazmat,
d.CMV,
d.CourtOrder,
GETDATE() As [EffectiveDate],
#user As [UpdatedBy],
GETDATE() As [UpdatedDate],
d.ConvictionACDID,
d.PassengerEndorsement
Into #hiddata
From #data d
Inner Join #surrogatemap sm On sm.CustomerEventID_Surrogate = d.CustomerEventID_Surrogate
Merge Into IADS..HistoryEventDetail
Using #hiddata As src On 1 = 0
When Not Matched Then
Insert
(
CustomerEventID,
HistoryEventTypeID,
CustomerEventCodeID,
ACDID,
State_Code,
County_ID,
CitationCDLHolderValueID,
OccurrenceDate,
Hazmat,
CMV,
CourtOrder,
EffectiveDate,
UpdatedBy,
UpdatedDate,
UnderlyingACDID,
PassengerEndorsement
)
Values
(
src.NewCustomerEventID,
src.HistoryEventTypeID,
src.CustomerEventCodeID,
src.ACDID,
src.State_Code,
src.County_ID,
src.CitationCDLHolderValueID,
src.OccurrenceDate,
src.Hazmat,
src.CMV,
src.CourtOrder,
src.EffectiveDate,
src.UpdatedBy,
src.UpdatedDate,
src.ConvictionACDID,
src.PassengerEndorsement
)
Output
src.NewCustomerEventID,
inserted.HistoryEventDetailID
Into #surrogateHIDmap;
Insert Into IADS..CustomerEventHierarchy
(
CustomerEventID,
RelatedCustomerEventID,
EffectiveDate,
UpdatedBy,
UpdatedDate
)
Select sm.NewCustomerEventID,
d.SanctionEventID,
GETDATE(),
#user,
GETDATE()
From #data d
Inner Join #surrogatemap sm On sm.CustomerEventID_Surrogate = d.CustomerEventID_Surrogate
Insert Into IADS..CourtFineDetail
(
HistoryEventDetailID,
ConvictionDate
)
Select s.NewHistoryEventDetailID,
d.ConvictionDate
From #hiddata d
Inner Join #surrogateHIDmap s On s.NewCustomerEventID = d.NewCustomerEventID
-- Remove the tie to the SUS077
Update IADS..CustomerEventHierarchy
Set EndDate = GETDATE(),
UpdatedBy = #user,
UpdatedDate = GETDATE()
Where CustomerEventHierarchyID In (Select CustomerEventHierarchyID From #data)
-- Build temp table containing the records that have already purged
Select ce.Cust_No,
ce.CustomerEventID,
ceh.CustomerEventHierarchyID
Into #disposedRecords
From IADS..CustomerEvent ce
Inner Join IADS..HistoryEventDetail hed On hed.CustomerEventID = ce.CustomerEventID
And hed.EndDate IS NULL
Inner Join IADS..CustomerEventCode cec On cec.CustomerEventCodeID = hed.CustomerEventCodeID
And hed.CustomerEventCodeID <> -51
Inner Join IADS..CustomerEventHierarchy ceh On ceh.CustomerEventID = ce.CustomerEventID
And ceh.EndDate IS NULL
Inner Join IADS..CustomerEvent ceSAN On ceSAN.CustomerEventID = ceh.RelatedCustomerEventID
And ceSAN.CustomerEventDispositionID IS NOT NULL
Inner Join IADS..CustomerSanctionDetail csd On csd.CustomerEventID = ceSAN.CustomerEventID
And csd.SanctionReasonCodeID = -320
Where ce.CustomerEventDispositionID IS NOT NULL
Order By ce.CustomerEventDispositionDate Desc
-- Un-purge all of the records that were previously tied to a SUS077
Update IADS..CustomerEvent
Set CustomerEventDispositionID = Null,
CustomerEventDispositionComment = Null,
CustomerEventDispositionDate = Null,
UpdatedBy = #user,
UpdatedDate = GETDATE()
Where CustomerEventID In (Select CustomerEventID From #disposedRecords)
-- Remove the records from the PURGEEventsReadyForPurge table
Delete
From IADS..PURGEEventsReadyForPurge
Where CustomerEventID In (Select CustomerEventID From #disposedRecords)
-- Remove tie of purged records
Update IADS..CustomerEventHierarchy
Set EndDate = GETDATE(),
UpdatedBy = #user,
UpdatedDate = GETDATE()
Where CustomerEventHierarchyID In (Select CustomerEventHierarchyID From #disposedRecords)
Delete From IADS..PURGEEventsReadyForPurge Where PURGEEventsReadyForPurgeID In
(
Select PURGEEventsReadyForPurgeID
From IADS..PURGEEventsReadyForPurge p
Inner Join IADS..CustomerEvent ce On ce.CustomerEventID = p.CustomerEventID
And ce.CustomerEventDispositionID IS NULL
Inner Join IADS..CustomerEventCategory ceg On ceg.CustomerEventCategoryID = ce.CustomerEventCategoryID
Left Outer Join IADS..CustomerEventHierarchy ceh On ceh.CustomerEventID = ce.CustomerEventID
Left Outer Join IADS..CustomerEventHierarchy ceh2 On ceh2.RelatedCustomerEventID = ce.CustomerEventID
Where p.PurgeDate IS NOT NULL
)
Drop Table #disposedRecords
Drop Table #hiddata
Drop Table #surrogateHIDmap
Drop Table #surrogatemap
Drop Table #data
Commit
End Try
Begin Catch
Drop Table #disposedRecords
Drop Table #hiddata
Drop Table #surrogateHIDmap
Drop Table #surrogatemap
Drop Table #data
Rollback
End Catch
You can try any of these two things..
1. Update the compatiability level to 100.
ALTER DATABASE [dbname] SET COMPATIBILITY_LEVEL = 100
2. End the MERGE statement and the statement previous to MERGE with a semicolon (;)
Hope it works.

Resources