以前从未写过触发器。
需要有一个检查日期的插入和更新触发器,如果日期大于 25 日,则将该日期设置回该月的 25 日。
现在我正在尝试构建@newDate,但我不知道该怎么做。
当前代码:
CREATE TRIGGER [dbo].[setASDate]
ON [dbo].[AutoShip]
AFTER UPDATE, INSERT
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @DistID INT;
DECLARE @date INT;
DECLARE @month INT;
DECLARE @year INT;
IF UPDATE(DateNextShipment)
BEGIN
DECLARE @newDate datetime;
SELECT TOP 1 @DistID = DistID FROM INSERTED
SELECT TOP 1 @date = DATEPART(d, DateNextShipment) FROM INSERTED
SELECT TOP 1 @month = CONVERT(varchar(2),DATEPART(mm, DateNextShipment)) FROM INSERTED
SELECT TOP 1 @year = CONVERT(varchar(4),DATEPART(yyyy, DateNextShipment)) FROM INSERTED
@newDate = CONVERT(datetime,@year + '-' + @month + '-25')
If @date > 25
BEGIN
UPDATE AutoShip
SET DateNextShipment = @newDate, Day = 25
WHERE DistID = @DistID
END
END
END
编辑 - 更新了代码