Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL insert into related tables

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?

like image 482
spender Avatar asked Nov 27 '08 00:11

spender


People also ask

How do you insert data into a relational table?

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.

How can we create new records in related table in SQL?

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');


1 Answers

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());
like image 180
Bill Karwin Avatar answered Nov 11 '22 10:11

Bill Karwin