SQL服务器约束

时间:2017-03-08 12:54:32

标签: sql-server ms-access

我有两个问题我无法解决,你想要帮助吗? 我有一个包含四个字段的表,其中两个是相关的,因此只有其中一个必须写入值,另一个必须为NULL。我的意思是,如果两个字段都是field1和field2,那么表格应如下所示:

field1  field2
NULL  value -- correct
value  NULL -- correct
NULL  NULL -- incorrect
value  value  -- incorrect

有没有办法制作约束或索引,我不确定,在表的定义中所以字段应该像示例一样编写

如果不可能 第二个问题是,因为我正在使用MS ACCESS将记录放入表中,如何在表单中 在记录之前检查字段是否填写不正确以提醒用户必须编辑插入的信息。

先谢谢了。

1 个答案:

答案 0 :(得分:0)

You can try using trigger INSTEAD OF (but be careful...).  Another way can be to build a stored procedure to make or not insert / update, and call the stored procedure from application.  

Just for example (should be completed with check, error try, etc.):

CREATE TABLE T1 (ID int NOT NULL, field1 int, field2 int);  
ALTER TABLE T1 ADD CONSTRAINT T1_PK PRIMARY KEY(ID);  
GO
CREATE TRIGGER T1_TRG_INS ON T1   
INSTEAD OF INSERT    
AS  
BEGIN  
IF EXISTS (SELECT 1 FROM inserted i WHERE (i.field1 IS NULL AND i.field2 IS NULL) OR (i.field1 IS NOT NULL AND i.field2 IS NOT NULL))  
  BEGIN  
     PRINT 'Data error.  No data inserted.'  
  END   
  ELSE BEGIN  
         INSERT INTO T1 (ID, field1, field2) SELECT ID, field1, field2 FROM inserted  
        END  
END  
GO  
CREATE TRIGGER T1_TRG_UPD ON T1   
INSTEAD OF UPDATE   
AS  
BEGIN  
IF EXISTS (SELECT 1 FROM inserted i WHERE (i.field1 IS NULL AND i.field2 IS NULL) OR (i.field1 IS NOT NULL AND i.field2 IS NOT NULL))  
  BEGIN  
     PRINT 'Data error.  No data updated.'  
  END   
  ELSE BEGIN  
         UPDATE T1 SET field1=i.field1, field2=i.field2  
         FROM inserted i WHERE T1.ID = i.ID  
        END  
END  
GO  
----testing-----
SELECT * FROM T1  
INSERT INTO T1 (ID, field1, field2) VALUES (1, NULL, NULL);  -- NOT inserted  
INSERT INTO T1 (ID, field1, field2) VALUES (2, NULL, 1); -- inserted  
INSERT INTO T1 (ID, field1, field2) VALUES (3, 1, NULL); -- inserted  
INSERT INTO T1 (ID, field1, field2) VALUES (4, 1, 1); -- NOT inserted  

UPDATE T1 SET field1 = 1 WHERE ID=2   -- not updated  
UPDATE T1 SET field2 = 2 WHERE ID=2   -- updated  
UPDATE T1 SET field1 = NULL, field2=3 WHERE ID=2   -- updated  
UPDATE T1 SET field1 = 4, field2=NULL WHERE ID=2   -- updated  
UPDATE T1 SET field1 = 4, field2=5 WHERE ID=2   -- not updated