Having data from another table put in into check constraint

女生的网名这么多〃 提交于 2019-12-12 10:44:00

问题


I have table say table1 with a colum say checkColumn,

now I want to put a check constraint to the field checkColumn which would allow only data which is there in another table say table 2 for some conditions,

I tried this like this,

ALTER TABLE table1
ADD CHECK (checkColumn=(select field1 from table2 where field2='ABC') ) //the select is not scalar

but as I realized it doesn't allow sub-query string in the check condition,I searched a little and read I should use a foreign key,or trigger, or something else,but didn't really understand how to implement those examples here,so posting this as a separate question.


回答1:


Unfortunately you can not insert Sub Query into context of Check constraint. But here I would like give suggestion, You can use any trigger or function , You can use foreign key constraint to check data dependency I would like to share one example with function. e.g.

CREATE FUNCTION fn_Check_Rollnumber (
    @Rollnumber INT
)
RETURNS VARCHAR(10)
AS
BEGIN
    IF EXISTS (SELECT Rollnumber FROM Table_Student WHERE Rollnumber = @Rollnumber)
        return 'True'
    return 'False'
END

Now you can use this function in you Check context like,

ALTER TABLE Table_Fees 
    WITH CHECK ADD CONSTRAINT CK_RollCheck
    CHECK (fn_Check_Rollnumber(Rollnumber) = 'True')


来源:https://stackoverflow.com/questions/16100700/having-data-from-another-table-put-in-into-check-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!