我在SQL Server中创建触发器时出错

时间:2017-01-18 02:46:20

标签: sql sql-server triggers insert

我想在插入新记录后创建一个触发器,它应该捕获新的记录信息。

CREATE TRIGGER trg_AccountInsert
ON [dbo].[Accounts]
FOR INSERT
AS
BEGIN
    DECLARE @NewValue NVARCHAR(4000);
    DECLARE @Name NVARCHAR(256);
    DECLARE @CompanyName NVARCHAR(256);
    DECLARE @ContactPhone NVARCHAR(256);
    DECLARE @Status bit;
    DECLARE @OtherId int;

    SELECT @OtherId = i.AccountId FROM inserted i;
    SELECT @name = i.Name FROM inserted i;
    SELECT @CompanyName = i.CompanyName FROM inserted i;
    SELECT @ContactPhone = i.ContactPhone FROM inserted i;    
    SELECT @Status = i.[Status] FROM inserted i;

    SET @NewValue = N'[{
            "Name" : ' + @Name +',
            "CompanyDetails" : '+ @CompanyName +',
            "ContactPhone" : '+ @ContactPhone + ',
            "Status" : '+ @Status + '
        }]';

    PRINT @NewValue

    INSERT INTO Auditlog (OtherId, TableName, ActionDate, ActionBy, Operation, ActionType) 
    VALUES (@OtherId, 'Accounts', getdate(), '', 'Insert', 'Accounts');

    DECLARE @AuditlogId int;
    SET @AuditlogId = IDENT_CURRENT('dbo.Auditlog') ;

    INSERT INTO AuditlogDetails (AuditlogId, OldValue, NewValue) 
    VALUES (@AuditlogId, null, @NewValue);
END

但是我收到了错误:

  

Msg 402,Level 16,State 1,Procedure trg_AccountInsert,第79行
  数据类型nvarchar和bit在add运算符中不兼容。

请帮我解决此错误

1 个答案:

答案 0 :(得分:2)

希望这会对你有所帮助..简化&将一次用于多个插入。

注意:架构我只假设你的代码没有经过测试,因为我没有架构&我的数据。

CREATE TRIGGER trg_AccountInsert
ON [dbo].[Accounts]
FOR INSERT
AS
BEGIN
    INSERT INTO Auditlog (OtherId, TableName, ActionDate, ActionBy, Operation, ActionType)
        SELECT 
            i.AccountId, 'Accounts', getdate(), '', 'Insert', 'Accounts' 
        FROM 
            inserted i

    /*  --As per comments updated new insert below
    INSERT INTO AuditlogDetails (AuditlogId, OldValue, NewValue)
        SELECT 
            A.AuditlogId, NULL, N'[{
                "Name" : ' + ISNULL(i.NAME,'') +',
                "CompanyDetails" : '+ ISNULL(I.CompanyName,'') +',
                "ContactPhone" : '+ ISNULL(I.ContactPhone,'') + ',
                "Status" : '+ISNULL( CAST(i.[Status] AS VARCHAR(5)),'')+ '
              }]' 
        FROM 
            inserted i
        INNER JOIN 
            Auditlog A ON I.AccountId = A.OtherId
      */

    INSERT INTO AuditlogDetails (AuditlogId, OldValue, NewValue)
        SELECT 
            A.AuditlogId, NULL, N'[{
            '+CASE WHEN i.NAME IS NOT NULL THEN '"Name": '+ i.NAME ELSE '' END+
            ' '+ CASE WHEN i.CompanyName IS NOT NULL THEN '"CompanyDetails" : '+ i.CompanyName ELSE '' END+
            ' '+ CASE WHEN i.ContactPhone IS NOT NULL THEN '"ContactPhone" : '+ i.ContactPhone ELSE '' END+
            ' '+ CASE WHEN i.[Status] IS NOT NULL THEN '"Status" : '+  CAST(i.[Status] AS VARCHAR(5)) ELSE '' END+''
        FROM 
            inserted i
        INNER JOIN 
            Auditlog A ON I.AccountId = A.OtherId
END