2

データが入力されたテーブル タイプを TSQL-Merge のソースとして使用する。マージ後に select ステートメントを実行して、テーブル タイプのすべての列/行を取得したいのですが、「-1」値の代わりに、新しく挿入された ID が必要です。完全にセットベースの方法でこれを行うことができるかどうかわかりません。

これは、挿入の山を DB に送信し、同じオブジェクトを返す必要があるが、それぞれの ID 列の値が入力されている UI 用です。SQL JOIN 操作の「共通列」はありません。

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

*/

ありがとう。

4

1 に答える 1

3

ただし、現在のコードを少し変更することで、その結果セットを取得できます。

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
于 2012-06-29T21:15:04.607 に答える