简体   繁体   中英

How to set Default Constraint for top 100 or 5 rows in SQL

Is this possible to add constraint, like the one below, using this method?

I am getting an error.

ALTER TABLE students 
ADD CONSTRAINT Adding_Default_Date
    DEFAULT 1 FOR (SELECT TOP 5 * FROM students);

In SQL Server, Check constraints only apply to individual rows.

Also, a Default constraints cannot access other rows.

It is not entirely clear from your description what you are trying to achieve.

If you want a Default constraint, but with your own custom logic, you might be able to achieve your goal with a Trigger.

CREATE TRIGGER Adding_Default_Date ON students
AFTER INSERT
AS Begin
  UPDATE s
  SET my_column = ...
  FROM student AS s
  JOIN inserted AS i
    ON i.key = s.key
End

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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