2013-04-05 78 views
2

我使用SQL Server 2008和merge into從表值參數得到我的數據。合併到和SCOPE_IDENTITY問題

CREATE PROCEDURE [dbo].[SP1] 
    (
    @p as TTVP readonly  
    ) 

AS 
declare @ThisId int 
Begin 

    Merge into [dbo].[FIRSTTABLE] tp 
    Using @p ps 
    on tp.ID = ps.ID 

    When Matched Then 
    Update 
    set tp.NAME = ps.NAME, 
    tp.myDATE = Getdate() 

    When Not Matched Then 

    insert (NAME, myDATE) 
    Values (ps.NAME, getDate()); 

    seclect @ThisId = identity_scope() 

    insert into SECONDTABLE (ID, myDATE) 
    select (@ThisId, Getdate()) 

    END 

我覺得我從來沒有scope_identity從我insert語句獲取的ID。

所以我的第一個更新和插入的作品,但我如何得到我的第二個插入插入的ID?

+0

@Richard固定的...... – NoviceDeveloper 2013-04-05 01:12:34

+0

我要迂腐約2兩件事:1 MERGE不適[標籤:SQL服務器2005年。 2.如果您還有其他問題,請隨時再提問 - 這樣做沒有任何費用。歡迎來到StackOverflow! (我已經更新。但是我的回答) – RichardTheKiwi 2013-04-05 01:48:51

+0

真的有人下來投票呢? – NoviceDeveloper 2013-04-05 12:05:04

回答

3

這表明如何從MERGE語句記錄輸出數據。請注意,OUTPUT子句在MERGE中的所有分支上運行,包括UPDATE和INSERT部分。然後使用inserted.id和deleted.id之間的不匹配來確定實際插入的內容。 OUTPUT子句展示瞭如何發揚從inserted虛擬表name列。

use tempdb; 

-- create the test tables and table type 
create table dbo.FirstTable (
    ID int identity primary key, 
    NAME sysname, 
    myDATE datetime); 
GO 
create table dbo.SecondTable (
    ID int primary key, 
    myDATE datetime, 
    NAME sysname); 
GO 
create type TTVP as TABLE(ID int, NAME sysname); 
GO 

-- create the procedure 
CREATE PROCEDURE dbo.SP1 
    @p as TTVP readonly 
AS 
SET NOCOUNT ON; 

create table #cache (new_id int primary key, old_id int, name sysname); 

merge into dbo.firsttable tp 
using @p ps on tp.id = ps.id 
when matched then 
    update 
     set tp.name = ps.name, 
      tp.mydate = getdate() 
when not matched then 
    insert (name, mydate) 
    values (ps.name, getdate()) 
output inserted.id, deleted.id, inserted.name into #cache; 

insert into dbo.secondtable (id, mydate, name) 
select new_id, getdate(), name 
from #cache 
where old_id is null; 
GO 

-- set up some test data (2 rows) 
truncate table dbo.FirstTable; 
insert dbo.FirstTable values ('abc', getdate()); 
insert dbo.FirstTable values ('ghi', getdate()-1); 
GO 

-- execute the procedure 
declare @p TTVP; 
insert @p values (1, 'abc'),(2, 'xyz'),(3, 'def'); 
exec dbo.SP1 @p; 

-- check the results 
select * from dbo.firsttable 
select * from dbo.secondtable 
+2

我可以有也只是增加了一個'WHERE NOT EXISTS'從表變量插入但得到絕對病拔牙的。 – 2013-04-05 01:26:55