SQL服务器约束数据

SQL服务器约束数据,sql,sql-server,Sql,Sql Server,我有两个表产品和供应商 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

我有两个表产品和供应商

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
)
我想:三星的产品必须是电视、手机或平板电脑。 帮帮我

数据库


我想要“SupplierCode4”,因为供应商提供“食品”

如果我理解您的意思是正确的,您需要为每个供应商定义表中允许的产品类型。
我认为您需要一个表来定义哪些供应商允许哪些产品类型,然后您可以在触发器或客户机中强制执行此操作

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

table ProductType (ID, Name)
这保存着像这样的信息

(1, 'Television'), (2, 'Tablet'), (3, 'Mobi'), (4, 'Food'), and so on...
然后在
产品
表中将字段
类型
替换为ProductTypeID

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

table AllowedProducts (ID, SupplierCode, ProductTypeID)
最后,您可以在客户端或触发器中检查此规则,如果您希望将此规则保留在数据库中

插入数据时,您可以检查所选
产品的
ProductTypeID
是否存在于所选“供应商”的表
AllowedProducts
中,如果没有,则拒绝插入。

您无法通过这种方式实现,请在
检查
约束中执行类似操作,因为值取决于不同的属性桌子

最直接的方法是创建触发器。这个是在插入之后。它只是删除不可接受的行。您可以进行实验,使其
而不是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 

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

到目前为止您尝试了什么?您熟悉
检查
约束吗?()你试试看,我不知道怎么用这个函数,但我不知道怎么用。欢迎来到stackoverflow。我们在这里提供帮助,但这不是一个代码编写服务。这里的问题预计会显示在发布问题之前试图解决问题的一些努力。请阅读并回答相应的问题。我尝试了,非常感谢,我做到了。我将表Product中的“Type”删除到表“Supplier”中,但我想要一个答案是查询,您能帮助我吗?如果您发布一些示例数据,可能会有所帮助。最好为
ProductType
创建一个新表,并在
Product
表中使用它。正如我的回答中的例子所示,你能提供详细信息吗?你需要的详细信息在我的回答中。非常感谢,我会的。