2014-03-31 2 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. 
--========================================================= 

그래서 추가했다 내 출력 필드는 다음과 같습니다.

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 
) 

이제 모두 정상적으로 작동합니다.