sql-server - (TRIGGER) if cell1 = 'value' THEN INSERT INTO table (date) VALUES (CURRENT_TIMESTAMP)
问题描述
我需要在 SQL Server 中创建一个触发器,该触发器每次从列“status”='Baja' 中的值触发
CREATE TRIGGER trg_triggerName
ON dbo.table1
AFTER UPDATE
AS
BEGIN
IF status = 'Baja' THEN BEGIN
INSERT INTO dbo.table1 (fechaBaja)
VALUES (CURRENT_TIMESTAMP)
END
END
GO
我收到此错误消息
消息 207,级别 16,状态 1,过程 trg_FechaBaja,第 3 行 [批处理开始第 34 行]
列名“状态”无效。
IF status = 'Baja' THEN BEGIN
在这一行中,“状态”给了我消息“无效的列名'状态'”,我 100% 确定我的列具有该名称。
IN RESUME:得到一个名为 table1 的表,其中有一列名为“status”,另一列名为“fechaBaja”
每次“状态”值更改为“Baja”时,我都需要触发并更新单元格“fechaBaja”current_timestamp
所有的操作都在同一个table1
.
解决方案
首先,你想要一个update
,而不是insert
。
Second, A trigger in SQL Server is fired once per statement, not once per row. This means that if the update statement that fired the trigger have updated multiple rows, your trigger will be fired once, and include data about these rows in the inserted
and deleted
tables.
Third, You need to make sure that the update statement inside the trigger will not raise it again. Do that by configuring the database.
The code you need is something like this:
CREATE TRIGGER trg_triggerName ON dbo.table1
AFTER UPDATE AS
BEGIN
UPDATE t
SET fechaBaja = CURRENT_TIMESTAMP
FROM dbo.table1 As T
INNER JOIN Inserted As I
ON T.<PrimaryKey> = I.<PrimaryKey>
INNER JOIN Deleted As D
ON T.<PrimaryKey> = D.<PrimaryKey>
WHERE I.[status] = 'Baja'
AND (D.[Status] IS NULL OR D.[Status] <> 'Baja')
END
GO
推荐阅读
- graphql - 在 GraphQL 中填充对象并将其传递给请求参数
- c# - 收藏中的收藏
- apache-spark - 使用 apache bahir 的 pyspark MQTT 结构化流
- android - GrantPermissionRule 未解析的引用
- javascript - 如何在 hapi.js 上的路径上使用 hapi-auth-jwt2 身份验证?
- c# - 如何使用signalR c#MVC接收用户特定的消息?
- c# - 使用 XSLT 进行 C# 对象映射的问题
- python - 如何将以下 json 数据转换为 dataFrame?
- java - 与 JDBC 一起使用时,Java Executor 服务未关闭线程
- ajax - d3更改加载的ajax数据