在sql中实现0..1关系

Implementing 0..1 relationship in tsql

我有一个 table,我想删除很多空列,但我不确定我的方向是否正确。

这里是展示我想要的示例 SQL(从产品中删除数量):

CREATE TABLE [Products]([Id] [int] NOT NULL,[Name] [varchar](50))
CREATE TABLE [StockProducts]([Id] [int] NOT NULL,[Quantity] [int])
go
insert into Products (Id, [Name]) values (1,'Socks')
insert into Products (Id, [Name]) values (2,'Gloves')
CREATE VIEW ProductStockView as select P.Id, SP.Quantity from Products P left join StockProducts SP on P.Id = SP.Id
go
select * from ProductStockView
go
update ProductStockView set Quantity = 2 where Id = 1

我非常希望更新能够在我的 StockProducts table 中提供一个插入,因为我拥有来自 Products 的所有 ID,并且我现有的代码将继续工作。

是否有这方面的模式,或者首选方法是在视图上添加更新触发器?现在更新语句给出:0 行受影响。

根据两条评论进行编辑:两个 table 的 ID 应被视为主键(用于 Entity Framework 等框架)。我的真实示例当然是我示例中称为 Products 的 table 是一个旧的 table,我们有 75 列,ProductStockView 是我想在我的部分代码中替换它的内容。

感谢您的评论。这正是我所需要的。我会在这里留下答案:

create trigger ProductStockViewUpdateTrigger
on ProductStockView instead of update
as
MERGE StockProducts as target
USING (SELECT Id, Quantity from inserted) as source
    ON target.Id = source.Id
WHEN MATCHED
    AND target.Quantity != source.Quantity
        THEN UPDATE 
            SET target.Quantity = source.Quantity
WHEN NOT MATCHED by target
THEN 
    INSERT ([Id], [Quantity])
    values (source.id, source.quantity);