0
我正在使用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'))
'CROSS JOIN'會產生笛卡爾乘積嗎? 'CROSS JOIN'比'INNER JOIN'有什麼優勢? – buck1112
@ buck1112。 。 。這似乎是你的疑問的意圖。但是,你的插入可能只會產生一個'id',所以笛卡爾的產品不會失控。 –
更新:我已經將它應用到我的更大的測試表中,現在我得到了似乎是笛卡爾積的東西:第一個表(它生成輸出ID)有1768行受到影響,而其他表中每個表都有3125824(1768平方)行受到影響。這些仍然是全部插入,在插入之前表中沒有數據存在。調查這種不良結果的原因是一個好的步驟?謝謝 – buck1112