【问题标题】:SQL Server Select After Merge Join on ColumnSQL Server 在列上合并联接后选择
【发布时间】:2012-06-29 20:47:30
【问题描述】:

使用填充的表类型作为 TSQL-Merge 的源。我想在合并后执行一个 select 语句, 检索表类型的所有列/行,但不是'-1'值,我想要新的 插入的 ID。我不确定我能否以完全基于集合的方式做到这一点,可以吗?

这适用于将一堆插入发送到数据库中的 UI,并且需要返回相同的对象,但填充了它们的每个 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

*/

谢谢。

【问题讨论】:

    标签: sql sql-server-2008 select join


    【解决方案1】:

    但是您可以通过稍微修改当前代码来获得该结果集:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多