2014-03-31 29 views
0

當我在生產系統中運行更新時,通常會將記錄保存到備份表中,以便在需要時很容易恢復。在更新語句中使用OUTPUT

我想使用OUTPUT子句完成此操作,有人可以幫助下面的語法嗎?

SELECT @@SERVERNAME 
go 
use Product 
go 


BEGIN TRANSACTION T1 

--this is what I would like to achieve using the OUTPUT CLAUSE: 
--SELECT * 
--INTO tablebackups.dbo._MM_20140331_ItemDetail 
--FROM ItemDetail 

-- now the update code: 

SELECT @@TRANCOUNT AS [Active Transactions] 
    ,@@SERVERNAME as [Server Name] 
    ,DB_NAME() as [Database Name] 

declare @CurrentUser nvarchar(128), 
    @CurrentDate datetime 

set @CurrentUser = suser_sname() 
set @CurrentDate = getdate() 

Update ItemDetail 
Set IsActive = 0, 
    BuyingStatus = 'Deleted', 
    ModifiedBy = @CurrentUser, 
    ModifiedDate = @CurrentDate, 
    ModifiedCount = ModifiedCount + 1 

output deleted.* into tablebackups.dbo._MM_20140331_ItemDetail -- <----- This is what I  would like to do 

FROM ItemDetail 

Where ItemID in (
2319848, 
2319868, 
2319888, 
2319908, 
2319928, 
2319938, 
2319948, 
2319958, 
2319968, 
2319988, 
2320008, 
2320028, 
2320048, 
2320068, 
2320078, 
2320088, 
2320098, 
2320108 
) 


--COMMIT 
--ROLLBACK 

感謝和問候 馬塞洛

回答

1

我現在的工作,爲什麼它不工作之前的原因有二:

1)輸出不創建新表。 解決這個我用下面的代碼:

select * 
into tablebackups.dbo._MM_20140331_ItemDetail_output 
from ItemDetail 
where 1 = 0 
--(0 row(s) affected) 

2)我更新了時間戳字段,這是給我下面的錯誤表:

--========================================================= 
-- I had to specify the fields -- just because of the error below: 

--Msg 273, Level 16, State 1, Line 40 
--Cannot insert an explicit value into a timestamp column. 
--Use INSERT with a column list to exclude the timestamp column, 
--or insert a DEFAULT into the timestamp column. 
--========================================================= 

所以我不得不添加我的OUTPUT字段如下:

declare @CurrentUser nvarchar(128), 
@CurrentDate datetime 

set @CurrentUser = suser_sname() 
set @CurrentDate = getdate() 

Update ItemDetail 
Set IsActive = 0, 
BuyingStatus = 'Deleted', 
ModifiedBy = @CurrentUser, 
ModifiedDate = @CurrentDate, 
ModifiedCount = ModifiedCount + 1 


output deleted.[ItemID] 
    ,deleted.[IsActive] 
    ,deleted.[CreatedBy] 
    ,deleted.[CreatedDate] 
    ,deleted.[ModifiedBy] 
    ,deleted.[ModifiedDate] 
    ,deleted.[ModifiedCount] 
    ,deleted.[BuyingStatus] 
into tablebackups.dbo._MM_20140331_ItemDetail_output 
                ([ItemID] 
                ,[IsActive] 
                ,[CreatedBy] 
                ,[CreatedDate] 
                ,[ModifiedBy] 
                ,[ModifiedDate] 
                ,[ModifiedCount] 
                ,[BuyingStatus]) 

FROM ItemDetail 

Where ItemID in (
2319848, 
2319868, 
2319888, 
2319908, 
2319928, 
2319938, 
2319948, 
2319958, 
2319968, 
2319988, 
2320008, 
2320028, 
2320048, 
2320068, 
2320078, 
2320088, 
2320098, 
2320108 
) 

現在一切正常。