SQL服务器约束数据

时间:2018-10-08 08:41:14

标签: sql sql-server

我有2个表格“产品和供应商”

create table Product(
    ProductCode int not null primary key,
    Name varchar(50) not null ,
    PurchasePrice numeric(20,3) not null,
    SellPrice numeric(20,3) not null ,
    Type varchar(50) not null,
    SupplierCode int not null 
)
go 

create table Supplier(
    SupplierCode int not null primary key,
    SupplierName varchar(50) not null ,
    Address varchar(50) not null
)

我想要:三星的产品必须是电视,手机或平板电脑。 救救我。

数据库enter image description here

我想要“ SupplierCode <> 4”,因为供应商提供“食品”

2 个答案:

答案 0 :(得分:0)

如果我理解您的观点正确,那么您想为每个供应商定义表中允许使用的产品类型。
我认为您需要一个表来定义哪些供应商可以使用哪些产品类型,然后您可以在触发器或客户中强制使用该表。

首先,您需要一个表来定义产品的种类

table ProductType (ID, Name)

其中包含

之类的信息
(1, 'Television'), (2, 'Tablet'), (3, 'Mobi'), (4, 'Food'), and so on...

然后将Type表中的Product字段替换为ProductTypeID

现在您可以使用一个表来定义每个供应商可能拥有的产品类型

table AllowedProducts (ID, SupplierCode, ProductTypeID)

最后,您可以在客户端中进行检查,或者如果您希望将此规则保留在数据库中,则可以在触发器中进行检查
插入数据时,您可以检查所选{Supplier`的表ProductTypeID中是否存在所选Product的{​​{1}},如果没有,则拒绝插入。

答案 1 :(得分:0)

由于值取决于不同的表,因此无法在check约束中像这样执行操作。

最直接的方法是创建触发器。这是插入后的。它只是删除不可接受的行。您可以尝试将其设置为instead of insert

CREATE TRIGGER insertProduct  
ON Sales.Product  
AFTER INSERT, UPDATE   
AS 

    delete from inserted a
    join Supplier b on a.SupplierCode  = b.SupplierCode
    where 
    (b.Supplier = 'Samsung' and a.Type not in ('phone', whatever you need...))
    or (b.Supplier = 'different' and a.Type not in (...))
    --here you put any additional logic for different suppliers

    if @@ROWCOUNT > 0
        RAISERROR ('Couldn't insert into table', 16, 10);  
GO 

根据您的情况,您还可以做的是仅通过存储过程来插入表。然后将支票放入存储过程中。

相关问题