gpt4 book ai didi

SQL插入相关表

转载 作者:行者123 更新时间:2023-12-02 10:49:08 25 4
gpt4 key购买 nike

在我看来,这似乎是 SQL/数据库开发中经常出现的问题,但我对这一切都是新手,所以请原谅我的无知。

我有 2 张 table :

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

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]

我想在轨道表中插入一个新条目。这还涉及在 trackstrings 表中插入新条目,并确保轨道中的外键列 trackstringid 指向 trackstring 中的新条目。实现这一目标最有效的方法是什么?

最佳答案

首先,插入到 TrackStrings 中,并从列列表中省略主键列。这将调用其 IDENTITY 列,该列会自动生成一个值。

INSERT INTO [dbo].[TrackStrings] ([String]) 
VALUES ('some string');

其次,插入 Tracks 并将函数 SCOPE_IDENTITY() 指定为其 TrackStringId ,它返回当前范围内的 IDENTITY 列生成的最新值

INSERT INTO [dbo].[Tracks] ([TrackStringId], [Time]) 
VALUES (SCOPE_IDENTITY(), CURRENT_TIMESTAMP());

关于SQL插入相关表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/322601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com