2

I have a problem. I created a table in Microsoft SQL and I would like one column to take not negative values. For example, EmployeeSalary column type is int and it hasn't a negative value.

3
  • 3
    Use a CONSTRAINT. Commented Apr 20, 2018 at 8:41
  • ...or a trigger to raise errors (but I agree that constraint is better here) Commented Apr 20, 2018 at 8:47
  • Are you sure you want to add this constraint? One never thought interest rates could go negative, but they did ;-) Commented Apr 20, 2018 at 8:49

3 Answers 3

7

Here is the solution of your problem:

Use CHECK while creating Table like this:

CREATE TABLE Table_name
(
    col1 int CHECK (col1 >= 0)
)

OR

If you want to make a column to reject negative number, after creating the table then you can do like this:

ALTER TABLE Table_Name ADD CONSTRAINT constraint_name CHECK (col_name >= 0);
Sign up to request clarification or add additional context in comments.

Comments

0

If you want to set condition when creating the table try:

EmployeeSalary money CHECK (EmployeeSalary>= 0)

If you just want to check during some script execution you can use if :

if(@Var > 0) begin

....

end

1 Comment

You can't use IF in a query, nor should you. That's what the WHERE clause is for
0

go tools>options>designer

"prevent changes that require table re-creation" this one should be unchecked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.