Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL Server 2005, how do I set a column of integers to ensure values are greater than 0?

This is probably a simple answer but I can't find it. I have a table with a column of integers and I want to ensure that when a row is inserted that the value in this column is greater than zero. I could do this on the code side but thought it would be best to enforce it on the table.

Thanks!

I was in error with my last comment all is good now.

like image 758
osp70 Avatar asked Oct 15 '08 15:10

osp70


People also ask

How do I limit integers in SQL?

If you want to limit the range of an integer column you can use a check constraint: create table some_table ( phone_number integer not null check (phone_number between 0 and 9999999999) );

How do you do greater than condition in SQL?

You can use the > operator in SQL to test for an expression greater than. In this example, the SELECT statement would return all rows from the customers table where the customer_id is greater than 6000. A customer_id equal to 6000 would not be included in the result set.

Can you use >= in SQL?

SQL Greater than or equal to ( >= ) operator The greater than equal to operator is used to test whether an expression (or number) is either greater than or equal to another one.


1 Answers

You can use a check constraint on the column. IIRC the syntax for this looks like:

create table foo (
    [...]
   ,Foobar int not null check (Foobar > 0)
    [...]
)

As the poster below says (thanks Constantin), you should create the check constraint outside the table definition and give it a meaningful name so it is obvious which column it applies to.

alter table foo
  add constraint Foobar_NonNegative
      check (Foobar > 0)

You can get out the text of check constraints from the system data dictionary in sys.check_constraints:

select name
      ,description
  from sys.check_constraints
 where name = 'Foobar_NonNegative'
like image 155
ConcernedOfTunbridgeWells Avatar answered Oct 11 '22 10:10

ConcernedOfTunbridgeWells