我有一个可以为空的FK字段的表。我把它做成了nullablle以避免更换装载机。
为了实现(广告商)* 1(货币),我写了一个简单的触发器:
ALTER TRIGGER InsertedAdvertisersDefaultCurrency
ON dbo.Advertisers
FOR INSERT
AS
UPDATE Advertisers
SET Currency_Id=(SELECT TOP 1 Id FROM Currencies WHERE Name='USD')
WHERE Currency_Id=NULL
我的问题基本上是关于我如何在每个插页上检查整个表的空行。
我觉得我应该使用插入的表(?)
这是表格:
CREATE TABLE [dbo].[Advertisers](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[Currency_Id] [int] NULL,
CONSTRAINT [PK_Advertisers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Advertisers] WITH CHECK ADD CONSTRAINT [FK_CurrencyAdvertiser1] FOREIGN KEY([Currency_Id])
REFERENCES [dbo].[Currencies] ([Id])
GO
ALTER TABLE [dbo].[Advertisers] CHECK CONSTRAINT [FK_CurrencyAdvertiser1]
GO
答案 0 :(得分:1)
是的,您应该只更新插入的记录:
UPDATE Advertisers
SET Currency_Id=(SELECT TOP 1 Id FROM Currencies WHERE Name='USD')
WHERE Id in (select Id from inserted)
或者您可以在该字段中使用默认值
ALTER TABLE [dbo].[Advertisers] ADD CONSTRAINT [DF_Advertisers_Currency_Id] DEFAULT ((101)) FOR [Currency_Id]
GO
其中101是美元ID