Is there anyway to change a column data type so that it will accept only negative values?

It's SQL Server 2014 Azure.

有帮助吗?

解决方案

CREATE TABLE t ( n INTEGER NOT NULL CHECK (n < 0) );

works in most RDBMS I know.

Edit: A comment by @IMSop prompts me to specify why I wrote “most RDMS I know:” it is well known (and very unfortunate) that CHECK constraints aren’t honored by MySQL. In MySQL, you have to use triggers instead. Another option is to switch to MariaDB.

其他提示

This can be achieved (at least in Sql Server) by using a CHECK constraint.

From the above post:

CHECK constraints enforce domain integrity by limiting the values that are accepted by one or more columns. You can create a CHECK constraint with any logical (Boolean) expression that returns TRUE or FALSE based on the logical operators. For example, the range of values for a salary column can be limited by creating a CHECK constraint that allows for only data that ranges from $15,000 through $100,000. This prevents salaries from being entered beyond the regular salary range. The logical expression would be the following: salary >= 15000 AND salary <= 100000.

许可以下: CC-BY-SA归因
不隶属于 dba.stackexchange
scroll top