0

Is there an option I can select in SQL management studio, when an int is entered into a it must be unique from all the other columns in that table.

Id Name Code 1 John 3545 2 Mark 454 3 Jim 989

If the user tried to create an account: 4 Mick 3545 - this would fail?

2
  • You could always do a select to find out what's there. But that's never going to be reliable. You should always let the DB set up unique IDs for you (auto increment). Commented Apr 10, 2014 at 17:00
  • It looks like the OP already has an identity column with "Id". You can do what Akash specified and add a unique constraint to the "Code" column. A common example for this is when you want to restrict duplicate usernames for an app. Commented Apr 10, 2014 at 17:10

4 Answers 4

2

You could add UNIQUE constraints on the columns which you want unique

ALTER TABLE TableName 
ADD CONSTRAINT ConstraintName UNIQUE (ColumnName); 
GO
Sign up to request clarification or add additional context in comments.

Comments

2

What you're asking for sounds like an Identity column. If you make your primary key an identity, you don't need to worry about inserting it - it is auto-incremented with inserts and guaranteed to be unique.

CREATE TABLE Users
(
    ID int NOT NULL AUTO_INCREMENT,
    //...
    PRIMARY KEY (ID)
)

Here is more documentation on the syntax

Comments

1

Make Code primary key in your database.

Comments

0

Yes, you can add unique constraint as part of column definition. Note that if column is primary key, it is unique by definition. See MSDN Create Table page, section on column constraints.

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.