This seems to me to be the kind of issue that would crop up all the time with SQL/database development, but then I’m new to all this, so forgive my ignorance.
I have 2 tables:
CREATE TABLE [dbo].[Tracks]( [TrackStringId] [bigint] NOT NULL, [Id] [bigint] IDENTITY(1,1) NOT NULL, [Time] [datetime] NOT NULL, CONSTRAINT [PK_Tracks] 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].[Tracks] CHECK CONSTRAINT [FK_Tracks_AudioStreams] GO ALTER TABLE [dbo].[Tracks] WITH CHECK ADD CONSTRAINT [FK_Tracks_TrackStrings] FOREIGN KEY([TrackStringId]) REFERENCES [dbo].[TrackStrings] ([Id]) GO ALTER TABLE [dbo].[Tracks] CHECK CONSTRAINT [FK_Tracks_TrackStrings] GO
and
CREATE TABLE [dbo].[TrackStrings]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [String] [nvarchar](512) NOT NULL, CONSTRAINT [PK_Strings] 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]
I want to insert a new entry into the tracks table. This will also involve inserting a new entry in the trackstrings table, and ensuring that the foreign key column trackstringid in tracks points to the new entry in trackstrings. What is the most efficient means of achieving this?
First, insert into
TrackStrings, omitting the primary key column from the column list. This invokes itsIDENTITYcolumn which generates a value automatically.Second, insert into
Tracksand specify as itsTrackStringIdthe functionSCOPE_IDENTITY(), which returns the most recent value generated by anIDENTITYcolumn in your current scope.