I have a table with a nullable FK field. I made it nullablle to avoid changing the loader.
In order to achieve (Advertisers)* 1(Currencies), I wrote a simple trigger:
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
My question is basically about how I am checking the whole table for null rows on every insert.
I feel like I should be using the inserted table (?)
Here’s the table:
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
Yes, you should just update the insertd records:
Or you may use a default value in that field
Where 101 is the USD id