Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Check constraint with ref to outside table

Author  Topic 

tuka
Starting Member

26 Posts

Posted - 2008-09-04 : 18:20:16

I am using the sql server 2005 express
I am trying to add a check constraint to a table A
using sql server management studio express

the check constraint uses a user defined function called
countHousing which returns an integer and is used
so:
counthousing(a) < b

where a = id column of associated table B i.e. the foreign key of row being inserted in table A
where b = noOfRooms column of asssociated table B

As you can see I need to pass in 1 value found in another table B.

How do I accomplish this ? can I use a select query in place of b ? Could you just give a snipet as I cant find any examples....

TIA

nathans
Aged Yak Warrior

938 Posts

Posted - 2008-09-04 : 21:44:44
hard to follow, but I think this will get you what you need:

Create a udf that evaluates the check constraint and returns a bit, udf_isLessThanHousing or whatever. Inside that you can do the noOfRooms count to see if a < b (referencing the FK table). Then in your check constraint you resolve by dbo.udf_isLessThanHousing(a) = 1 which will only need to constrain the column a which is available in the inserted table.

Make sense?

Nathan Skerl
Go to Top of Page

nathans
Aged Yak Warrior

938 Posts

Posted - 2008-09-04 : 22:00:47
simple example:



create function dbo.udf_isLessThanMaxA (@Col int)
returns bit
as
begin
declare @return bit

select @Return = case when @Col < max(ColA) then 1 else 0 end
from dbo.TableA

return @Return
end;
go

set nocount on;
go

-- create and populate first table
create table dbo.tableA (colA int);
go
insert into dbo.tableA
select 1 union select 2

-- now create second table that has check constaint that inserted valued must be less than a column in first table (tableA)
create table dbo.tableB (colB int constraint chkCount check (dbo.udf_isLessThanMaxA(colB) = 1))

-- now try to violate check by inserting value greater than 2 (which is max in first table)
-- * FAILS
insert into dbo.tableB
values (3)

-- try to insert value that is less than max in first table
-- * SUCCEEDS
insert into dbo.tableB
values(1)



-- cleanup
drop table dbo.tableA
drop table dbo.tableB
drop function dbo.udf_isLessThanMaxA


Nathan Skerl
Go to Top of Page
   

- Advertisement -