【问题标题】:Trying to fill table with default value试图用默认值填充表格
【发布时间】:2021-02-06 17:26:25
【问题描述】:

我有 2 个表、供应商和产品。我正在尝试用随机信息填充它们。 表产品,列供应商_id。我将此列 default 的值设置为 -1

我在尝试在给定列中插入默认值的行出现错误。 检查下面的代码,帖子底部的错误消息。

供应商:

CREATE TABLE Suppliers
(
 id int primary key identity(1,1),
 "name" nvarchar(50) not null,
 telephone nvarchar(50) default 'N/A',
 "address" nvarchar(50) default 'N/A'

)
INSERT INTO Suppliers (name,telephone,address)
values ('Supplier 1', '021-555-333', 'Jovana Petrovica 72, Beograd 11000'),
        ('Supplier 2', '021-555-333', 'Branka Radicevica 13, Zrenjanin 23000'),
        ('Supplier 3', '021-555-333', 'Bulevar Oslobodjenja 30A, Novi Sad 21000')

产品:

CREATE TABLE Products
(
 id int primary key identity(1,1),
 "name" nvarchar(50) not null,
   price float default 0,
  supplier_id int default -1,
  foreign key (supplier_id) references Suppliers(id) ON DELETE SET DEFAULT 

)
INSERT INTO Products (name, price, supplier_id)
values ('Product 1', 800, 3),
        ('Product 2', 1300, 1),
        ('Product 3', 230, 2),
        ('Product 4', 570, 3),
        ('Product 5', 1225, 2);
INSERT INTO Products (name, price)
values ('Product 6', 80); // I read online this is the way to insert default values (?)

错误信息:

INSERT 语句与 FOREIGN KEY 约束“FK__Products__suppli__03F0984C”冲突。冲突发生在数据库“Tehna”、表“dbo.Suppliers”、列“id”中。 该语句已终止。

【问题讨论】:

  • 不能将supplier_id -1插入Products,因为Products表中没有supplier_id -1,所以外键约束拒绝。
  • 它只是说你的默认值根据你定义的外键不正确,也许将默认设置为NULL
  • 请连同sql标签一起标记您的DBMS
  • @jarlh 几秒钟前我才想出来的,哈哈。我不建议在 DB 中阅读在线 NULL 值。但我想外键唯一的选择是这里的NULL,对吧?
  • 不要相信您在 Internet 上阅读的所有内容。 NULL 值是有目的的。

标签: sql sql-server default-value


【解决方案1】:

我猜默认的 'supplier_id' 应该大于 0 或 null,因为它与 Suppliers 中的 'id' 有关,它是主键也是一个整数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-23
    • 2011-11-24
    • 2019-01-19
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多