2

下面是用于捕获 SQL 表上的更新/插入的触发器。我不知道为什么,但是每当更新完成时,从字符串转换日期和/或时间时,我都会收到错误消息转换失败。这是事务日志表的结构:

CREATE TABLE [dbo].[TransactionLog](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [TransactionDate] [datetime] NOT NULL,
    [Operator] [varchar](35) NOT NULL,
    [TableName] [varchar](50) NOT NULL,
    [Action] [char](1) NOT NULL,
    [TableString] [nvarchar](255) NOT NULL,
    [UserId] [char](6) NULL,
 CONSTRAINT [PK_TransactionLog] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

这是正在更新的表格:

CREATE TABLE [dbo].[AgentContEd](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [sNumber] [int] NOT NULL,
    [StateCode] [char](3) NOT NULL,
    [CourseCode] [char](6) NOT NULL,
    [DateTaken] [date] NOT NULL,
    [ExpirationDate] [date] NULL,
    [CourseHours] [smallint] NOT NULL,
    [Method] [varchar](15) NULL,
    [LastChangeOperator] [char](8) NOT NULL,
    [LastChangeDate] [datetime] NOT NULL,
    [ControlId] [int] NULL,
 CONSTRAINT [PK_AgentContEd] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY]

这是导致头痛的触发器......

BEGIN
    INSERT INTO dbo.TransactionLog 
    (
        TransactionDate, 
        Operator, 
        TableName, 
        Action, 
        TableString, 
        UserId
    )
    SELECT 
        LastChangeDate,
        'Op',
        @tableName,
        @action,
        CAST(
          'ID:'             + CAST(ISNULL(Id,             'NULL') as char(4))
        + ' SymNum:'        + CAST(ISNULL(sNumber,  'NULL') as char(10))
        + ' StateCode:'     + ISNULL(StateCode,           'NULL')
        + ' DateTaken:'     + CAST(ISNULL(DateTaken,      'NULL') as nvarchar(9))
        + ' ExpDate:'       + CAST(ISNULL(ExpirationDate, 'NULL') as nvarchar(9))
        + ' CourseCode:'    + ISNULL(CourseCode,          'NULL')
        + ' Hours:'         + CAST(ISNULL(CourseHours,    'NULL')  as char(3))
        + ' Mthd:'          + ISNULL(Method,              'NULL')
        As char(255)), 
        LastChangeOperator
    FROM inserted
END
4

1 回答 1

1

尝试

    + ' DateTaken:'     + ISNULL(CAST(DateTaken as varchar(9)),      'NULL')
    + ' ExpDate:'       + ISNULL(CAST(ExpirationDate as varchar(9)), 'NULL') 

我使用varchar它似乎毫无意义,如果你无论如何nvarchar都要将字符串投射到最后。char

此外,您可能需要使用CONVERT样式而不是CAST存储有用的东西。SELECT CAST(getdate() as nvarchar(9))为我返回Sep 28 20

格式列表在这里

于 2012-09-28T16:41:13.147 回答