从另一个表中将标识列值插入表中?

时间:2013-07-15 19:38:35

标签: sql sql-server

create table #test (a int identity(1,1), b varchar(20), c varchar(20))

insert into #test (b,c) values ('bvju','hjab')
insert into #test (b,c) values ('bst','sdfkg')
......
insert into #test (b,c) values ('hdsj','kfsd')

如何将从上面插入语句填充的标识值(#test.a)插入#sample表(另一个表)

create table #sample (d int identity(1,1), e int, f varchar(20))

insert into #sample(e,f) values (identity value from #test table, 'jkhjk')
insert into #sample(e,f) values (identity value from #test table, 'hfhfd')
......
insert into #sample(e,f) values (identity value from #test table, 'khyy')

请问任何人请解释我如何为更大的记录集(数千条记录)实现这一点?

我们可以使用while循环和scope_identity吗?如果是,请解释我们该怎么做?

如果我从选择查询插入#test会是什么情景?

插入#test(b,c) select ... from ...(数千条记录)

我如何捕获身份值并将该值用于另一个值(#sample) 插入#sample(e,f) select(来自#test的身份值),......来自....(千记录) -

3 个答案:

答案 0 :(得分:7)

您可以使用output子句。从文档(强调我的):

  

OUTPUT子句从每个受影响的行返回信息或表达式   通过INSERT,UPDATE,DELETE或MERGE语句。这些结果可以   返回处理应用程序以用于此类事物   确认消息,存档和其他此类应用程序   要求。 结果也可以插入表格或表格中   变量。此外,您还可以捕获OUTPUT的结果   嵌套INSERT,UPDATE,DELETE或MERGE语句中的子句,以及   将这些结果插入目标表或视图中。

像这样:

create table #tempids (a int) -- a temp table for holding our identity values

insert into #test 
(b,c) 
output inserted.a into #tempids -- put the inserted identity value into #tempids
values 
('bvju','hjab')

然后你问......

  

如果插入来自选择,该怎么办?

它的工作方式相同......

insert into #test 
(b,c) 
output inserted.a into #tempids -- put the inserted identity value into #tempids
select -- except you use a select here
 Column1
,Column2
from SomeSource

无论是从值,派生表,执行语句,dml表源还是默认值插入,它的工作方式都相同。 如果您插入1000条记录,则#tempids将获得1000个ID。

答案 1 :(得分:0)

我刚刚用输出子句写了一个“基于集合”的样本。

在这里。

IF OBJECT_ID('tempdb..#DestinationPersonParentTable') IS NOT NULL
begin
        drop table #DestinationPersonParentTable
end



IF OBJECT_ID('tempdb..#DestinationEmailAddressPersonChildTable') IS NOT NULL
begin
        drop table #DestinationEmailAddressPersonChildTable
end



CREATE TABLE #DestinationPersonParentTable
(
PersonParentSurrogateIdentityKey int not null identity (1001, 1), 
SSNNaturalKey int, 
HireDate datetime
)



declare @PersonOutputResultsAuditTable table
(
SSNNaturalKey int, 
PersonParentSurrogateIdentityKeyAudit int
)





CREATE TABLE #DestinationEmailAddressPersonChildTable
(
DestinationChildSurrogateIdentityKey int not null identity (3001, 1), 
PersonParentSurrogateIdentityKeyFK int, 
EmailAddressValueNaturalKey varchar(64),
EmailAddressType int
)





-- Declare XML variable

DECLARE @data XML;

-- Element-centered XML

SET @data = N'
<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Person>
        <SSN>222222222</SSN>
        <HireDate>2002-02-02</HireDate>
    </Person>

    <Person>
        <SSN>333333333</SSN>
        <HireDate>2003-03-03</HireDate>
    </Person>

    <EmailAddress>
        <SSNLink>222222222</SSNLink>
        <EmailAddressValue>g@g.com</EmailAddressValue>
        <EmailAddressType>1</EmailAddressType>
    </EmailAddress>

    <EmailAddress>
        <SSNLink>222222222</SSNLink>
        <EmailAddressValue>h@h.com</EmailAddressValue>
        <EmailAddressType>2</EmailAddressType>
    </EmailAddress>

    <EmailAddress>
        <SSNLink>333333333</SSNLink>
        <EmailAddressValue>a@a.com</EmailAddressValue>
        <EmailAddressType>1</EmailAddressType>
    </EmailAddress>

    <EmailAddress>
        <SSNLink>333333333</SSNLink>
        <EmailAddressValue>b@b.com</EmailAddressValue>
        <EmailAddressType>2</EmailAddressType>
    </EmailAddress>

</root>

';




INSERT INTO #DestinationPersonParentTable ( SSNNaturalKey ,  HireDate )

output inserted.SSNNaturalKey , inserted.PersonParentSurrogateIdentityKey  into @PersonOutputResultsAuditTable ( SSNNaturalKey , PersonParentSurrogateIdentityKeyAudit)

SELECT T.parentEntity.value('(SSN)[1]', 'INT') AS SSN,
       T.parentEntity.value('(HireDate)[1]', 'datetime') AS HireDate
FROM @data.nodes('root/Person') AS T(parentEntity)
/* add a where not exists check on the natural key */
where not exists (
    select null from #DestinationPersonParentTable innerRealTable where innerRealTable.SSNNaturalKey = T.parentEntity.value('(SSN)[1]', 'INT') )
;

/* Optional.  You could do a UPDATE here based on matching the #DestinationPersonParentTableSSNNaturalKey = T.parentEntity.value('(SSN)[1]', 'INT')
You could Combine INSERT and UPDATE using the MERGE function on 2008 or later.
 */


select 'PersonOutputResultsAuditTable_Results' as Label, * from @PersonOutputResultsAuditTable


INSERT INTO #DestinationEmailAddressPersonChildTable (  PersonParentSurrogateIdentityKeyFK ,  EmailAddressValueNaturalKey , EmailAddressType )
SELECT  par.PersonParentSurrogateIdentityKeyAudit , 
        T.childEntity.value('(EmailAddressValue)[1]', 'varchar(64)') AS EmailAddressValue,
        T.childEntity.value('(EmailAddressType)[1]', 'INT') AS EmailAddressType
FROM @data.nodes('root/EmailAddress') AS T(childEntity)
/* The next join is the "trick".  Join on the natural key (SSN)....**BUT** insert the PersonParentSurrogateIdentityKey into the table */
join @PersonOutputResultsAuditTable par on par.SSNNaturalKey = T.childEntity.value('(SSNLink)[1]', 'INT')
where not exists (
    select null from #DestinationEmailAddressPersonChildTable innerRealTable where innerRealTable.PersonParentSurrogateIdentityKeyFK = par.PersonParentSurrogateIdentityKeyAudit AND  innerRealTable.EmailAddressValueNaturalKey = T.childEntity.value('(EmailAddressValue)[1]', 'varchar(64)'))
;



print '/#DestinationPersonParentTable/'
select * from #DestinationPersonParentTable


print '/#DestinationEmailAddressPersonChildTable/'
select * from #DestinationEmailAddressPersonChildTable


select SSNNaturalKey , HireDate , '---' as Sep1 , EmailAddressValueNaturalKey , EmailAddressType , '---' as Sep2, par.PersonParentSurrogateIdentityKey as ParentPK , child.PersonParentSurrogateIdentityKeyFK as childFK from #DestinationPersonParentTable par join #DestinationEmailAddressPersonChildTable child
on par.PersonParentSurrogateIdentityKey = child.PersonParentSurrogateIdentityKeyFK



IF OBJECT_ID('tempdb..#DestinationPersonParentTable') IS NOT NULL
begin
        drop table #DestinationPersonParentTable
end


IF OBJECT_ID('tempdb..#DestinationEmailAddressPersonChildTable') IS NOT NULL
begin
        drop table #DestinationEmailAddressPersonChildTable
end

答案 2 :(得分:-1)

insert into #test (b,c) values ('bvju','hjab')
insert into #sample(e,f) values (@SCOPE_IDENTITY(), 'jkhjk')

@SCOPE_IDENTITY()返回最后使用的标识值