在 CREATE TABLE 的末尾添加 DEFAULT CONSTRAINT

Add DEFAULT CONSTRAINT at the end of a CREATE TABLE

如何在 CREATE 的末尾添加 DEFAULT CONSTRAINT TABLE?

我想在最后有一个独立的行像

CREATE TABLE myTable (
  table_id       INT NOT NULL,
  firstColumn    NVARCHAR(10),
  secondColumn   INT,
  thirdColumn    INT,
  CONSTRAINT DEF_secColumn DEFAULT 0 FOR secondColumn
)

它不起作用。我收到错误消息

Incorrect syntax near 'for'.

你能帮帮我吗?非常感谢转发!

您应该在需要默认值的字段旁边使用默认值,例如:

CREATE TABLE myTable (
  table_id       INT NOT NULL,
  firstColumn    NVARCHAR(10),
  secondColumn   INT DEFAULT 0,
  thirdColumn    INT
)

或者如果你真的想添加约束,你可以稍后使用 ALTER TABLE 添加它:

CREATE TABLE myTable (
  table_id       INT NOT NULL,
  firstColumn    NVARCHAR(10),
  secondColumn   INT,
  thirdColumn    INT
)

ALTER TABLE myTable ADD CONSTRAINT DEF_secColumn DEFAULT 0 FOR [secondColumn]

或@jeroen-mostert 建议的第三个选项

CREATE TABLE myTable (
  table_id       INT NOT NULL,
  firstColumn    NVARCHAR(10),
  secondColumn   INT CONSTRAINT DEF_secColumn DEFAULT 0,
  thirdColumn    INT
)