开发者

How to Setup a Constraint to Restrict Char Field to a Set of Values?

I am having a brain fart today. In SQL Server (currently using 2008), how do I开发者_开发百科 setup a char field to only accept a specific series of chars (roughly eight case sensitive letters)? And I need to re-use this "custom field" in several tables.

I know I could setup another table and put a foreign key constraint on it. Is that the only way?


If you use the double negative construct, this only allows chars A to H

ALTER TABLE MyTable WITH CHECK
   CONSTRAINT CK_MyTable_MyColChars CHECK (
     MyColChars COLLATE Latin1_General_BIN NOT LIKE '%[^ABCDEFGH]%'
     )

For re-use, use a udf

CREATE FUNCTION dbo.CheckChars (@Value varchar(100))
RETURNS bit
AS
BEGIN
   RETURN (CASE WHEN @Value NOT LIKE '%[^ABCDEFGH]%' THEN 1 ELSE 0 END)
END
GO

... CHECK (
      dbo.CheckChars (MyColChars) = 1
     )

If you wanted A_F, semi-colon and space it'd be '%[^ABCDEF; ]%' for example


You'll probably want to look into creating a check constraint. This post has a matching pattern you could build off of:

How to make SQL Server 2008 Check Constraint of a table Allow Only Certain characters?

In order to get the case sensitive matching, remove 'a-z' in the pattern and create the check constraint with a case sensitive collation. This ensures case sensitive matching even if the server and database are case insensitive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜