Annoscia
Annoscia

Reputation: 117

SQL server insert trigger

I'm a novice at SQL server and I have a task to create a trigger that will insert/update a customer's status to 'Blocked' in a payment is overdue.

How could I check to say something like the following within a trigger?

if getdate() > dateDue
then update status = 'Blocked'
end if

Many thanks for you help in advance

Upvotes: 1

Views: 360

Answers (3)

Michael Fredrickson
Michael Fredrickson

Reputation: 37388

Here's an implementation of Martin's suggestion to create a non-persisted computed column:

ALTER TABLE dbo.YourTable 
ADD Status AS CASE WHEN DueDate < GETDATE() THEN 'Blocked' ELSE 'Not Blocked' END

Upvotes: 1

Jim
Jim

Reputation: 6881

If you want to have this status updated when dueDate becomes < today, as opposed to only updating it when the dueDate for the record is modified, you should schedule a stored procedure via SQL Sever Agent and have it run a simple update to set the statuses for any records where dueDate < today. You can run this nightly, or every hour, or whatever you need.

If you don't want to run Agent, you could do it with a Windows service that you write code for (more of a pain to set up), or even a batch file that runs from a Windows Task, but obviously Agent is the most convenient way to do this.

Upvotes: 0

Jim
Jim

Reputation: 6881

I don't have time to really test this, so there might be some problems / syntax issues, but here's something that should give you an idea how to go about it. Basically, your trigger should fire whenever the value of "dateDue" is changed. It should iterate through the "inserted" values in case more than one record was updated, and for each record in "inserted", if the new "dateDue" value is > the current time, you update that record and set the status to 'Blocked'.

CREATE TRIGGER myTriggerName
ON myTable
AFTER INSERT, UPDATE
AS
IF UPDATE(dateDue)
BEGIN
  DECLARE @currPk INT
  DECLARE @currDateDue DATETIME
  DECLARE @today DATETIME
  DECLARE inserted_Cursor CURSOR FOR
  SELECT myTableID, dateDue, GETDATE() FROM Inserted

  OPEN inserted_Cursor;
  FETCH NEXT FROM inserted_Cursor INTO @currPk, @currDateDue, @today
  WHILE @@FETCH_STATUS = 0

    BEGIN
      IF(@currDateDue < @today)
      UPDATE myTable SET status = 'Blocked' WHERE myTableID = @currPk

      FETCH NEXT FROM inserted_Cursor INTO @currPk, @currDateDue, @today
    END;

  CLOSE inserted_Cursor;
  DEALLOCATE inserted_Cursor;
END;

Upvotes: 0

Related Questions