如何将主键从一个表作为外键插入到辅助表中

时间:2014-01-10 20:10:40

标签: sql sql-server tsql

我正在创建一个包含两个表submissionssubmittedItems的示例数据库。我正在使用示例数据填充此表,我想知道如何使用第一个表中的主键填充第二个表。

我正在测试的脚本工作得很好但是我正在通过简单地镜像计数来插入外键。由于这是一个新表,它可以正常工作,因为它们都以相同的数字开头。我的问题是,如果表中已有数据,我将如何检索输入到提交表中的最后一条记录的PK?我知道在使用Identity时我可以使用SELECT SCOPE_IDENTITY()来输入最后一个身份,但不确定要用于其他任何事情的正确select语句。或者我误解了Scope_Identity()的使用,它确实检索了输入的最后一个PK /身份?正如你所看到的,我不是sql的专家,所以如果有更好的方法,我会欢迎任何建议。

提前致谢,

use SampleRecords
GO
--create two test tables
CREATE TABLE submissions
(submission_id int Identity(1,1) primary key not null,
submissionName varchar(150),
dateSubmitted datetime)

CREATE TABLE submissionItems
(submissionitems_id int identity(1,1) primary key,
fk_submission_id int  not null,
item varchar(150),
CONSTRAINT fk_submission_id foreign key (fk_submission_id) references submissions (submission_id))

--populate tables with sample data
DECLARE @totalRecords int 
SET @totalRecords = 0
DECLARE @currentKey int

WHILE @totalRecords < 500
BEGIN

SET @totalRecords = @totalRecords + 1
INSERT INTO dbo.submissions (submissionName, dateSubmitted)
VALUES
('submission record ' + cast(@totalRecords AS varchar(3)), SYSDATETIME())

INSERT INTO dbo.submissionItems (fk_submission_id, item)
VALUES
(@totalRecords, 'a new record item for submission '+ cast(@totalRecords AS varchar(3)))

-- I tried using scope_identity as follows but could not get the syntax correct
-- ('submission record ' + cast(Select Scope_Identity() AS varchar(3)), SYSDATETIME())

END

2 个答案:

答案 0 :(得分:2)

SCOPE_IDENTITY@@IDENTITYIDENT_CURENT函数将仅返回最后的IDENTITY值。如果有一个包含许多行的INSERT语句(参见下面的示例),那么这些函数对您无法帮助。

相反,我会使用OUTPUT clause(它需要SQL Server 2005 +)。

实施例

CREATE TABLE dbo.Orders 
(
 order_nbr  INT IDENTITY(1,1) PRIMARY KEY,
 tname      VARCHAR(25),
 prod_type  INT
);

DECLARE @OrderNumbers TABLE (order_nbr INT PRIMARY KEY);

INSERT INTO dbo.Orders (order_nbr, tname, prod_type)
OUTPUT inserted.order_nbr INTO @OrderNumbers    
SELECT 'x', 1
UNION ALL SELECT 'y', 1
UNION ALL SELECT 'z', 2;

SELECT * FROM @OrderNumbers; -- It displays generated order numbers

INSERT INTO ....
SELECT ... FROM @OrderNumbers; 

答案 1 :(得分:0)

是的,只需使用ScopeIdentity ......

--populate tables with sample data
DECLARE @totalRecords int 
SET @totalRecords = 0
DECLARE @currentKey int

WHILE @totalRecords < 500
BEGIN
    SET @totalRecords = @totalRecords + 1

    INSERT INTO dbo.submissions (submissionName, dateSubmitted)
        VALUES ('submission record ' + cast(@totalRecords AS varchar(3)), SYSDATETIME())

    Set @currentKey = Scope_Identity()

    INSERT INTO dbo.submissionItems (fk_submission_id, item)
        VALUES (@currentKey, 'a new record item for submission '+ cast(@totalRecords AS varchar(3)))
END