创建列,检查总数是否超过另一列... SQL Server

时间:2018-03-03 22:27:12

标签: sql sql-server

SQL Server 2016

我有一个包含这些列的表:

CREATE TABLE [dbo].[Site]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [SiteId] [int] NOT NULL,
    [WellId] [int] NOT NULL,
    [TotalOil] [int] NOT NULL,

)

我正在创建另一个表:

CREATE TABLE [dbo].[Reserves]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [SiteId] [int] NOT NULL,
    [WellId] [int] NOT NULL,
    [TotalOil] [int] NOT NULL,
    [TotalGas] [int] NOT NULL,
    ....
)

我希望其中一列有一个约束,即总数不能超过TotalOil表的Site

我尝试了以下内容:

ALTER TABLE [dbo].[Reserves]  
    ADD CHECK (TotalOil <= [dbo].Site.[TotalOil])

这会在SSMS中引发错误:

  

多部分标识符&#34; dbo.Site.TotalOil&#34;无法受约束。

如何添加约束以确保TotalOil表中的Reserves列不超过TotalOil表中的Site列值?谢谢

2 个答案:

答案 0 :(得分:2)

您需要创建一个从Site表返回TotalOil的函数,并在check约束中引用它。

CREATE FUNCTION dbo.TotalOil(@SiteId INT) RETURNS INT 
AS BEGIN 
RETURN (
 SELECT 
  TotalOil
 FROM dbo.Site
 WHERE SiteId = @SiteId)
END

然后你可以在保留表的检查约束中引用它:

ALTER TABLE dbo.Reserves ADD CHECK ( TotalOil <= dbo.TotalOil(SiteId))

答案 1 :(得分:1)

您可以使用用户定义的函数或触发器来执行此操作。

select  id, goods, sum(quantities)
from    yourTable
group by id, goods

然后create function usp_get_totaloil ( @siteId int ) returns int as begin declare @TotalOil int; select @TotalOil = s.TotalOil from [dbo].Site s where s.SiteId = @siteId; return @TotalOil; end; 约束看起来像:

check