How can I create a CHECK constraint on a VARCHAR column in SQL Server specifying a minimum data length?

谁说我不能喝 提交于 2019-12-18 05:37:28

问题


I have a VARCHAR(30) column in a Microsoft SQL Server database. I'd like to add a CHECK constraint that does not allow a value in the column to be less than 3 characters. What is the expression I must use?


回答1:


use:

ALTER TABLE [dbo].[YOUR_TABLE]
ADD CONSTRAINT [MinLengthConstraint] CHECK (DATALENGTH([your_column]) > 2)

Reference:

  • DATALENGTH vs LEN
  • SQL SERVER – 2005 Constraint on VARCHAR(MAX) Field To Limit It Certain Length


来源:https://stackoverflow.com/questions/4426005/how-can-i-create-a-check-constraint-on-a-varchar-column-in-sql-server-specifying

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!