在我看来,这是一个随着SQL /数据库开发一直出现的问题,但后来我对这一切都不熟悉,所以请原谅我的无知.
我有2张桌子:
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]
我想在track表中插入一个新条目.这还将涉及在tracktrings表中插入一个新条目,并确保轨道中的外键列tracktringid指向tracktrings中的新条目.实现这一目标的最有效方法是什么?
首先,插入TrackStrings
,省略列列表中的主键列.这将调用其IDENTITY
自动生成值的列.
INSERT INTO [dbo].[TrackStrings] ([String]) VALUES ('some string');
其次,插入Tracks
并指定为TrackStringId
函数SCOPE_IDENTITY()
,该函数返回当前作用域中IDENTITY
列生成的最新值.
INSERT INTO [dbo].[Tracks] ([TrackStringId], [Time]) VALUES (SCOPE_IDENTITY(), CURRENT_TIMESTAMP());
如果您正在使用SQL Server 2005或更高版本并且在单个中插入大量记录INSERT
,则可以在此处查看OUTPUT
或OUTPUT INTO
选项以使用第二个插入中的标识,而无需"重新查找"要获取的行所有的价值观.IDENTITY