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?
In syntax, First, you must specify the name of the table. After that, in parenthesis, you must specify the column name of the table, and columns must be separated by a comma. The values that you want to insert must be inside the parenthesis, and it must be followed by the VALUES clause.
First, insert into TrackStrings , omitting the primary key column from the column list. This invokes its IDENTITY column which generates a value automatically. INSERT INTO [dbo]. [TrackStrings] ([String]) VALUES ('some string');
First, insert into TrackStrings
, omitting the primary key column from the column list. This invokes its IDENTITY
column which generates a value automatically.
INSERT INTO [dbo].[TrackStrings] ([String])
VALUES ('some string');
Second, insert into Tracks
and specify as its TrackStringId
the function SCOPE_IDENTITY()
, which returns the most recent value generated by an IDENTITY
column in your current scope.
INSERT INTO [dbo].[Tracks] ([TrackStringId], [Time])
VALUES (SCOPE_IDENTITY(), CURRENT_TIMESTAMP());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With