SQL Server INSERT / UPDATE触发器连接日期字符串

时间:2013-08-27 16:04:03

标签: sql-server triggers concatenation insert-update

之前从未写过触发器。

需要在插入和更新上设置一个检查日期的触发器,如果​​该日期大于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

编辑 - 更新了代码

1 个答案:

答案 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')