我正在编写 SQL Server 2012 中的脚本(作为经典 ASP 页面的后端),以从我的初始表 ( aaa_test_ap
) 中选择所有行并将它们分布在我的其他 3 个表 ( aaa_test_users
、aaa_test_users_positions
和aaa_test_users_education
) 中。
我想获得 的标识aaa_test_users.ID
,一旦将一行插入其中,用于其他两个表插入,作为它们的 FK ( User_ID
),在同一个查询中。
INSERT INTO
是否可以在一个查询中 使用该方法获得身份?
我试过使用SCOPE_Identity()
,但它只返回最后一个值。
使用该OUTPUT
方法,我将如何利用它生成的表值,以便将第一个插入语句生成的值插入到接下来的两个语句中,每个语句都在正确的插入行中?
首先,表格:
CREATE TABLE [dbo].[aaa_test_sp]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](50) NULL,
[first_name] [nvarchar](50) NULL,
[last_name] [nvarchar](50) NULL,
[position] [nvarchar](50) NULL,
[phone] [nvarchar](50) NULL,
[education] [nvarchar](50) NULL,
[ListID] [int] NULL,
CONSTRAINT [PK_aaa_test_sp]
PRIMARY KEY CLUSTERED ([ID] ASC)
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[aaa_test_users]
(
[UserID] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](50) NULL,
[first_name] [nvarchar](50) NULL,
[last_name] [nvarchar](50) NULL,
CONSTRAINT [PK_aaa_test_users]
PRIMARY KEY CLUSTERED ([UserID] ASC)
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[aaa_test_users_positions]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [int] NULL,
[position] [nvarchar](50) NULL,
[phone] [nvarchar](50) NULL,
CONSTRAINT [PK_aaa_test_users_positions]
PRIMARY KEY CLUSTERED ([ID] ASC)
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[aaa_test_users_education]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[UserID] [int] NULL,
[education] [nvarchar](50) NULL,
CONSTRAINT [PK_aaa_test_users_education]
PRIMARY KEY CLUSTERED ([ID] ASC)
) ON [PRIMARY]
GO
这是我一直在处理的查询:
--declare @NewUserID nvarchar(50)
DECLARE @InsertOutput1 table (UserID nvarchar(50));
--insert, first, rows from sp to users, and get the autoNumber'ed ID,
--"NewUserID"
INSERT INTO aaa_test_users (UserName, first_name, last_name)
OUTPUT inserted.UserID INTO @InsertOutput1
SELECT
UserName, first_name, last_name
FROM aaa_test_sp
WHERE (ListId = '1')
--select * from @InsertOutput1
--SELECT SCOPE_IDENTITY() As NewUserID
--set @NewUserID=(SELECT SCOPE_IDENTITY() )
--now that the "NewUserID" has been generated,
--insert it, along with other columns,
--into the 'users_positions' table.
--print 'new user id is ' + @NewUserID
INSERT INTO aaa_test_users_positions (UserID, position, phone)
(SELECT
@NewUserID, position, phone
FROM aaa_test_sp
WHERE (ListId = '1')
)
--now that the "NewUserID" has been generated,
--insert it, along with other columns,
--into the 'users_education' table
--print @NewUserID
INSERT INTO aaa_test_users_education (UserID, education)
(SELECT @NewUserID, education
FROM aaa_test_sp
WHERE (ListId = '1'))