当我在生产系统中运行更新时,我通常会将记录保存到备份表中,以便在需要时可以轻松恢复。
我想使用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
感谢和问候 马塞洛
答案 0 :(得分:1)
我现在已经开始工作,之前没有工作的原因是2:
1)OUTPUT不会创建新表。 为了解决这个问题,我使用了以下代码:
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
)
现在一切正常。