2012-06-29 2 views
2

채워진 테이블 형식을 TSQL-Merge의 원본으로 사용. 병합 후에 select 문을 실행하고 싶습니다. 테이블 유형의 모든 열/행을 검색하지만 '-1'값 대신에 ID를 삽입하고 싶습니다. 나는 완벽하게 세트 기반 방식으로 이것을 할 수 있을지 확신하지 못한다.열에서 병합 후 SQL Server Select

이것은 DB에 삽입 파일을 보내고 동일한 객체를 다시 가져올 필요가 있지만 각 ID 열 값이 채워져 있어야합니다. 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 

*/ 

감사합니다.

답변

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