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
列值?谢谢
答案 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