简体   繁体   English

创建列时不允许为 0

[英]Do not allow 0 when creating column

I am creating a table in SQL Server and I have a column of decimal type that should not receive the value 0, how could I do that?我正在 SQL 服务器中创建一个表,并且我有一个decimal类型的列不应该接收值 0,我该怎么做?

CREATE TABLE Producto
(
    Idproducto [int] PRIMARY KEY NOT NULL 
        DEFAULT (NEXT VALUE FOR Idprod),
    Nombre [varchar](100) NOT NULL,
    Precio_Unitario DECIMAL (18,2) 
);

You can use a CHECK constraint.您可以使用CHECK约束。 For example:例如:

CREATE TABLE Producto
(
    Idproducto int PRIMARY KEY NOT NULL,
    Nombre varchar(100) NOT NULL,
    Precio_Unitario DECIMAL(18, 2),
    CONSTRAINT chk1 CHECK (Precio_Unitario <> 0)
);

Typical inserts will work well:典型的插入会很好地工作:

INSERT INTO Producto (Idproducto, Nombre, Precio_Unitario) 
VALUES (1, 'A', 2);

INSERT INTO Producto (Idproducto, Nombre, Precio_Unitario) 
VALUES (2, 'B', NULL);

But if you try:但如果你尝试:

INSERT INTO Producto (Idproducto, Nombre, Precio_Unitario) 
VALUES (3, 'C', 0);

You'll get an error:你会得到一个错误:

Msg 547 Level 16 State 0 Line 1消息 547 级别 16 State 0 行 1
The INSERT statement conflicted with the CHECK constraint "chk1". INSERT 语句与 CHECK 约束“chk1”冲突。 The conflict occurred in database "fiddle_914c4e0be5e144138dc870cf3d5a6ced", table "dbo.Producto", column 'Precio_Unitario'.冲突发生在数据库“fiddle_914c4e0be5e144138dc870cf3d5a6ced”、表“dbo.Producto”、列“Precio_Unitario”中。

Msg 3621 Level 0 State 0 Line 1消息 3621 级别 0 State 0 行 1
The statement has been terminated.该语句已终止。

See running example at db<>fiddle .请参阅db<>fiddle的运行示例。

You can create a check constraint, that will force all values in that column to be null or different from zero您可以创建一个检查约束,这将强制该列中的所有值都为 null 或不同于零

CREATE TABLE #Producto
(
    Idproducto [int]  PRIMARY KEY NOT NULL DEFAULT (NEXT VALUE FOR Idprod),
    Nombre [varchar](100) NOT NULL,
    Precio_Unitario DECIMAL  (18,2),
    constraint chk_Precio_Unitario check (Precio_Unitario is null or Precio_Unitario <> 0) 
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM