简体   繁体   English

状态缩写检查约束

[英]State Abbreviation check constraint

I want to create a check constraint for state abbreviations. 我想为状态缩写创建一个检查约束。 I only want to allow a two character insert for the State column. 我只想在“状态”列中插入两个字符。 What would be the code? 代码是什么? my code was: State VARCHAR(2) NOT NULL CONSTRAINT CK_StateAbbr CHECK (State like 'xx') 我的代码是:State VARCHAR(2)NOT NULL CONSTRAINT CK_StateAbbr CHECK(状态如“ xx”)

I am assuming putting the xx in there will only allow xx for the state. 我假设将xx放置在该位置仅允许xx进入该状态。 Would I put CHECK (State like '[AZ][AZ]')? 我可以输入CHECK(“ [AZ] [AZ]”之类的状态)吗?

With most versions of MySQL, it makes no difference. 对于大多数版本的MySQL,这没有什么区别。 A check constraint is accepted as syntax, but it is not implemented. check约束被接受为语法,但未实现。

That leaves you with several choices. 这给您几个选择。 First, ignore the issue. 首先,忽略该问题。 This would be the most common approach. 这将是最常见的方法。 Second, use a trigger. 其次,使用触发器。 That makes for messy code and is not optimal. 这会使代码混乱,而且不是最佳选择。

The third approach is to create a table with all valid state abbreviations. 第三种方法是创建带有所有有效状态缩写的表。 Then you can use a foreign key constraint, to ensure that the value is valid. 然后,您可以使用外键约束来确保该值有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM