SQL Server 更新移动到单独的列
Posted
技术标签:
【中文标题】SQL Server 更新移动到单独的列【英文标题】:SQL Server on update move to separate column 【发布时间】:2015-04-22 18:11:37 【问题描述】:我的公司需要Customer
表中的一列,该列将显示任何客户以前的地址数。每当地址更新时,此号码必须自动更新。
CREATE TRIGGER deleted_address ON tblcustomer
INSTEAD OF INSERT
AS
BEGIN
SET NOCOUNT ON
end
到目前为止,我有这个,但我遇到了一个问题,我不知道如何制作它,所以如果编辑客户的地址,它会将旧地址添加到名为 PreviousAddress
的新列中,然后更新CustomerAddress
【问题讨论】:
【参考方案1】:使用AFTER UPDATE
触发器:
CREATE TRIGGER deleted_address ON tblcustomer
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON
IF UPDATE (Address)
UPDATE t SET countPrev = countPrev + 1, oldAddress = d.Address
FROM tblcustomer t
JOIN INSERTED i ON t.customer_id = i.customer_id
JOIN DELETED d ON t.customer_id = d.customer_id
END
【讨论】:
【参考方案2】:要更新以前的地址,你可以这样写一个触发器。
CREATE TRIGGER trg_UpdateAddress
ON Customer
AFTER UPDATE
AS
BEGIN
DECLARE @id INT = (SELECT ID FROM DELETED)
UPDATE dbo.Customer SET PreviousAddress = (SELECT Address FROM DELETED )
WHERE ID = @id
END
【讨论】:
【参考方案3】:试试看这是否适合你:
CREATE TRIGGER deleted_address ON tblcustomer
AFTER UPDATE
AS
BEGIN
IF UPDATE (CustomerAddress)
UPDATE t
SET t.[PreviousAddress] = t.PreviousAddress + 1,
t.CustomerAddress = i.CustomerAddress
FROM tblcustomer t
JOIN INSERTED i ON t.customer_id = i.customer_id
END
GO
【讨论】:
那么,除非CustomerAddress
列受到影响,否则我的更新将被忽略?
好点,我更新到更新后...我一定错过了之前的那个。感谢收看!以上是关于SQL Server 更新移动到单独的列的主要内容,如果未能解决你的问题,请参考以下文章
从 Excel 更新 SQL Server 表,然后填充剩余的列数据