简体   繁体   English

SQL触发器,检查是否输入了某个值

[英]SQL trigger, check if certain value was entered

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

Now what to check: 现在检查一下:

If inserted value1 = null, change it to 0 如果插入value1 = null,则将其更改为0

How to do it via trigger? 如何通过触发器来做到这一点? I googled for examples and I have never ever done a trigger, so it is rather confusing. 我用谷歌搜索了一些例子,我从来没有做过触发器,所以它相当令人困惑。

So far got only this: 到目前为止只有这个:

CREATE TRIGGER testTrigger
ON myTable
AFTER INSERT, UPDATE, DELETE

You can add default value . 您可以添加默认值 This is how it's done for a new column. 这就是新列的完成方式。 For existing one you should add constraint. 对于现有的,您应该添加约束。 Check Update 2 检查更新2

ALTER TABLE table_name 
ADD column1 int NOT NULL DEFAULT(0)

Add a column with a default value to an existing table in SQL Server 将具有默认值的列添加到SQL Server中的现有表

UPDATE: 更新:

To set default value, you should update NULL values at first. 要设置默认值,首先应更新NULL值。

UPDATE table_name 
SET column1 = 0
WHERE column1 IS NULL

UPDATE 2: 更新2:

Try adding constraint 尝试添加约束

ALTER TABLE table_name 
ADD CONSTRAINT DF_column1 DEFAULT 0 FOR column1 

You could write this in the trigger: 你可以在触发器中写这个:

UPDATE T SET value1 =0
FROM   table_name T
JOIN   INSERTED I
ON     T.<id>=I.<id>
WHERE  I.value1 is null

INSERTED table which is accessible only within trigger will store the values that have inserted.. 只能在触发器中访问的INSERTED表将存储已插入的值。

INSERTED值上使用ISNULL

 SELECT ISNULL(INSERTED,0) FROM INSERTED

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM