SQL Server在列上合并联接后选择
使用填充的表类型作为TSQL合并的源。我想在合并后执行select语句, 正在检索表类型的所有列/行,但我希望使用新的 插入的id。我不确定我是否可以以完全基于集合的方式执行此操作,可以吗 这适用于将一堆插入发送到DB中的UI,它需要返回相同的对象,但每个对象的ID列值都已填充。SQL联接操作没有“公共列”SQL Server在列上合并联接后选择,sql,sql-server-2008,select,join,Sql,Sql Server 2008,Select,Join,使用填充的表类型作为TSQL合并的源。我想在合并后执行select语句, 正在检索表类型的所有列/行,但我希望使用新的 插入的id。我不确定我是否可以以完全基于集合的方式执行此操作,可以吗 这适用于将一堆插入发送到DB中的UI,它需要返回相同的对象,但每个对象的ID列值都已填充。SQL联接操作没有“公共列” CREATE TYPE instype AS TABLE( instypeid [smallint] NOT NULL, instext [varchar](64) NOT
CREATE TYPE instype AS TABLE(
instypeid [smallint] NOT NULL,
instext [varchar](64) NOT NULL
)
Go
create table #desttable ( instypeid smallint identity(1,1) primary key , instext varchar(64) )
Go
declare @newids table ( idvalue smallint )
declare @thing1 instype
insert into @thing1 values ( -1 , 'zero' )
insert into @thing1 values ( -1 , 'one' )
Merge #desttable desttbl
Using @thing1 srctbl
On desttbl.instypeid = srctbl.instypeid
When Not Matched Then
Insert ( instext )
Values ( instext )
Output inserted.instypeid Into @newids
;
/*
Wanted shape of the result set
instypeid instext
0 zero
1 one
*/
谢谢。但您可以通过稍微修改当前代码来获得该结果集:
if object_id('tempdb.dbo.#desttable') is not null
drop table #desttable
create table #desttable ( instypeid smallint identity(0,1) primary key
, instext varchar(64) )
Go
declare @inserted table ( idvalue smallint, instext varchar(64) )
declare @thing1 instype
insert into @thing1 values ( -1 , 'zero' ), ( -1 , 'one' )
Merge #desttable desttbl
Using @thing1 srctbl
On desttbl.instypeid = srctbl.instypeid
When Not Matched Then
Insert ( instext )
Values ( instext )
Output inserted.instypeid, inserted.instext Into @inserted
;
SELECT *
FROM @inserted