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.
| 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 Ausing sql server management studio expressthe check constraint uses a user defined function calledcountHousing which returns an integer and is used so:counthousing(a) < bwhere a = id column of associated table B i.e. the foreign key of row being inserted in table Awhere b = noOfRooms column of asssociated table BAs 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 |
 |
|
|
nathans
Aged Yak Warrior
938 Posts |
Posted - 2008-09-04 : 22:00:47
|
simple example:create function dbo.udf_isLessThanMaxA (@Col int)returns bitasbegindeclare @return bitselect @Return = case when @Col < max(ColA) then 1 else 0 endfrom dbo.TableAreturn @Returnend;goset nocount on;go-- create and populate first tablecreate table dbo.tableA (colA int);goinsert 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)-- * FAILSinsert into dbo.tableB values (3) -- try to insert value that is less than max in first table-- * SUCCEEDSinsert into dbo.tableB values(1)-- cleanupdrop table dbo.tableAdrop table dbo.tableBdrop function dbo.udf_isLessThanMaxA Nathan Skerl |
 |
|
|
|
|
|