如果不存在则添加约束
我想将“检查”约束添加到某个表,但首先我必须检查该约束是否存在。我的 SQL 脚本中有一些错误。正确的做法是什么?
ALTER TABLE public.ELEMENTS ADD CONSTRAINT IF NOT EXISTS elements_check CHECK ((t1_id IS NOT NULL) OR (t2_id IS NOT NULL));
I want to add the 'check' constraint to some table, but firstly I have to check if that constraint exists. I have some error in my SQL script. What is the corret way to do it ?
ALTER TABLE public.ELEMENTS ADD CONSTRAINT IF NOT EXISTS elements_check CHECK ((t1_id IS NOT NULL) OR (t2_id IS NOT NULL));
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用此语句来检查 SQL Server 中是否存在主键。
I use this statement to check wherever a Primary Key exists or not in SQL Server.
根据手册:
ALTER TABLE ... DROP CONSTRAINT IF EXISTS
确实存在ALTER TABLE ... ADD CONSTRAINT IF NOT EXISTS
不存在,因此您必须在 2. 之前执行 1. :
According to the manual :
ALTER TABLE ... DROP CONSTRAINT IF EXISTS
do existALTER TABLE ... ADD CONSTRAINT IF NOT EXISTS
doesn't existso you have to execute 1. before 2. :