MS SQL Server:主键,自动递增和插入失败

时间:2017-03-02 16:01:49

标签: sql-server

我有这个代码我从MySQL转换:

CREATE TABLE "odds_soccer" 
(
    "id" INT NOT NULL PRIMARY KEY ,
    "checked" DATETIME NOT NULL ,
    "bookmaker" VARCHAR(255) NOT NULL ,
    "gametime" DATETIME NOT NULL ,
    "team1" VARCHAR(255) NOT NULL ,
    "team2" VARCHAR(255) NOT NULL ,
    "odds_1" FLOAT NOT NULL ,
    "odds_x" FLOAT NOT NULL ,
    "odds_2" FLOAT NOT NULL 
);

INSERT INTO "odds_soccer" ("id", "checked", "bookmaker", "gametime", "team1", "team2", "odds_1", "odds_x", "odds_2") 
VALUES (null, '2017-03-02 16:00:00', 'example.com', '2017-03-02 04:30:00', 'MYTEAMA', 'MYTEAMB', '3.15', '3.15', '2.70');

唯一的问题是...它禁止使用null进行插入,这非常公平......

但是如何插入记录我只想让ID自动递增

我尝试了各种各样的变化 - 都失败了 - 我必须遗漏一些明显的东西......

1 个答案:

答案 0 :(得分:2)

正确的方法如下:

CREATE TABLE "odds_soccer" (
    "id" INT IDENTITY(1,1) PRIMARY KEY ,
    "checked" DATETIME NOT NULL ,
    "bookmaker" VARCHAR(255) NOT NULL ,
    "gametime" DATETIME NOT NULL ,
    "team1" VARCHAR(255) NOT NULL ,
    "team2" VARCHAR(255) NOT NULL ,
    "odds_1" FLOAT NOT NULL ,
    "odds_x" FLOAT NOT NULL ,
    "odds_2" FLOAT NOT NULL
);

这样,每次在表格中插入新记录时,id字段都会自动递增。 请注意,如果您的ID字段自动递增,则不必在insert语句中指定它。

INSERT INTO "odds_soccer" 
(
  "checked",
  "bookmaker",
  "gametime",
  "team1",
  "team2",
  "odds_1",
  "odds_x",
  "odds_2"
) 
VALUES (
  '2017-03-02 16:00:00',
  'example.com',
  '2017-03-02 04:30:00',
  'MYTEAMA',
  'MYTEAMB',
  '3.15',
  '3.15',
  '2.70'
);

Link to documentation(IDENTITY)