Using SQL Server, how do I script a constraint on a field in a table, so that the acceptable range of values is between 0 and 100?
+9
A:
ALTER TABLE Table
ADD CONSTRAINT CK_Table_Column_Range CHECK (
Column >= 0 AND Column <= 100 --Inclusive
)
Mark Brackett
2008-12-19 20:23:18
+2
A:
A check constraint like "fieldname BETWEEN 0 AND 100" should do it.
le dorfier
2008-12-19 20:25:22
+1
A:
Try:
ALTER TABLE myTableName
ADD CONSTRAINT myTableName_myColumnName_valZeroToOneHundred
CHECK (myColumnName BETWEEN 0 AND 100)
This check would be inclusive - here is some info about BETWEEN from MSDN: BETWEEN (Transact SQL)
Gunny
2008-12-19 20:25:52
+1
A:
According to me, the right question isn't "how" but "why".
This 0-100 rule sounds to me like a business rule. Why should it be implemented on the server/database side? If an incorrect value is entered, who will get the error message?
If the user gets the error message, wouldn't it be easier to have the code giving him the message before the transaction reaches the server?
What about range modification? May the rule change? I guess yes: rules ALLWAYS change. Can the range be updated from 0-100 to 101-200? In this case, what about values already entered in the database?
Philippe Grondier
2008-12-19 23:17:46