之前从未写过触发器。
需要在插入和更新上设置一个检查日期的触发器,如果该日期大于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
编辑 - 更新了代码
答案 0 :(得分:1)
声明varchar类型的变量@date和@month,然后将其用作:
SELECT TOP 1 @date = DATEPART(d, DateNextShipment) FROM INSERTED
SELECT TOP 1 @year= convert(varchar(4),DATEPART(yyyy, DateNextShipment)) FROM INSERTED
SELECT TOP 1 @month = convert(varchar(2),DATEPART(mm, DateNextShipment)) FROM INSERTED
@newDate = convert(datetime,@year+'-'+@month+'-'+'25')