【发布时间】:2011-09-02 13:26:28
【问题描述】:
我需要在table1 中插入多行,同时在table2 中插入一行,其中pkID 来自table1 和一个来自SP 参数的值。
我创建了一个存储过程,它使用表值参数执行批量插入,其中包含要插入到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子句可以为您提供该值。 -
如果我对您的理解正确并且您在 2008 年,请参阅 Using merge..output to get mapping between source.id and target.id
标签: sql-server