我有一个要求将多行插入到table1
中,并同时将一行插入table2
,pkID
table1
和一个来自SP参数的值。将批量行插入到SQL Server 2008中的两个表中
我创建了一个存储过程,该存储过程使用包含要插入到table1
中的行的表值参数执行批量插入。但我有一个问题,将table2
中的行插入到中,其中有与table1
对应的Id(标识)以及我已经通过的参数值。
有没有人实施过这个,或者有什么好的解决方案呢?
CREATE PROCEDURE [dbo].[oSP_TV_Insert]
@uID int
,@IsActive int
,@Type int -- i need to insert this in table 2
,@dTableGroup table1 READONLY -- this one is a table valued
AS
DECLARE @SQL varchar(2000)
DECLARE @table1Id int
BEGIN
INSERT INTO dbo.table1
(uID
,Name
,Contact
,Address
,City
,State
,Zip
,Phone
,Active)
SELECT
@uID
,Name
,Contact
,Address
,City
,State
,Zip
,Phone
,Active
,@G_Active
FROM @dTableGroup
--the above query will perform batch insert using the records from dTableGroup which is table valued
SET @table1ID = SCOPE_IDENTITY()
-- this below will perform inserting records to table2 with every Id inserted in table1.
Insert into table2(@table1ID , @type)
你能后的代码,你认为什么是不正常?如果您在获取插入记录的标识值方面存在问题,那么'INSERT'具有'OUTPUT'子句,它将为您提供该值。 – a1ex07
如果我已经正确理解你并且你在2008年看到[使用merge..output获取source.id和target.id之间的映射](http://stackoverflow.com/questions/5365629/using-merge-output- to-get-mapping-between-source-id-and-target-id) –
是的,马丁,你是对的。 – user335160