简体   繁体   中英

How to check attribute in SQL Server 2012 using regular expressions?

I need to insert an equipment model code, is a string formatted as:

AAA-0123456

It has to be, 3 uppercase letters, the "-" in the middle and 6 numbers, I need to have a constraint check (model code like regular expression) I think.

How can I do this?

You would do this via a check constraint, see here: http://www.w3schools.com/sql/sql_check.asp

Yes you can put regex in a check constraint, here is an example:

CREATE TABLE dbo.PEOPLE (
name VARCHAR(25) NOT NULL
, emailaddress VARCHAR(255) NOT NULL
, CONSTRAINT PEOPLE_ck_validemailaddress CHECK ( dbo.RegExValidate( emailaddress, N'^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$' ) = 1 )
) 

Your regular expression would be: [AZ][AZ][AZ][-][0-9][0-9][0-9][0-9][0-9][0-9][0-9]

Here is a great tool to build and test reg expr http://www.regexr.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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