插入查询的SQL Server错误

时间:2013-06-14 07:40:41

标签: sql sql-server-2008

我有一张表AuditTrail

当我运行此查询时:

INSERT INTO AuditTrail
                     ( EntityName, Date, [User], Action, OldValue
                      , NewValue, ModuleName, EntityRef, EntityAttribute
                      , EntityAltRef) 
VALUES (aaa, '2012-02-07 00:00:00.000', sa, DELETE, '11', aaa, aaa, sa, aaa, aaa)

我收到错误

Incorrect Syntax Near Keyword 'DELETE'

我在这里做错了什么?

这是表结构

ID                numeric(18, 0)  Unchecked
EntityName        nvarchar(60)    Unchecked
Date              datetime        Unchecked
[User]            sysname         Unchecked
Action            varchar(30)     Unchecked
OldValue          varchar(1024)   Checked
NewValue          varchar(1024)   Checked
ModuleName        varchar(6)      Checked
EntityRef         varchar(30)     Checked
EntityAttribute   varchar(60)     Checked
EntityAltRef      varchar(64)     Checked

3 个答案:

答案 0 :(得分:2)

在sa和delete之间添加'

INSERT INTO AuditTrail ( EntityName, Date, [User], Action, OldValue, NewValue, ModuleName, EntityRef, EntityAttribute, EntityAltRef) 
VALUES ('aaa','2012-02-07 00:00:00.000','sa','DELETE','11','aaa','aaa','sa','aaa','aaa')

sa是默认的admin用户,delete是SQL中的关键字,你必须将它们作为文字插入,这就是你必须通过'封装它们的原因,我假设aaa是一个字符串值为好。

答案 1 :(得分:1)

这是因为DELETE是一个保留关键字,所以你应该用引号转义,让数据库看不到它是一个字段而不是一个命令。您还在使用

INSERT INTO AuditTrail ( EntityName, Date, [User], Action, OldValue, NewValue, ModuleName, EntityRef, EntityAttribute, EntityAltRef) VALUES (aaa,'2012-02-07 00:00:00.000',sa,'DELETE','11',aaa,aaa,sa,aaa,aaa)

检查您的其他字段,并记住不是整数列的值需要用引号'

包围

答案 2 :(得分:1)

DELETE是命令,你不能直接使用它。在它周围单引号,所以databae会理解它是字符串而不是命令。

INSERT INTO AuditTrail
                     ( EntityName, Date, [User], Action, OldValue
                      , NewValue, ModuleName, EntityRef, EntityAttribute
                      , EntityAltRef) 
              VALUES (aaa,'2012-02-07 00:00:00.000'
                     ,sa,'DELETE','11',aaa,aaa,sa,aaa,aaa);