I'm totally new to SQL Server, I use version 2012.
I have a table with the following structure:
Attendance
--------------
TagID (FK)
SessionID (FK)
ScanningTime
I need to create a unique constraint based on two columns (TagID
and SessionID
)
I'm not sure how to do this. I have created a query and tried this code:
ALTER TABLE Attendance ADD CONSTRAINT UNIQUE NONCLUSTERED
(
TagID,
SessionID
)
But when I try to execute it, I receive this error:
Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'UNIQUE'.
What is the proper way to alter the table using SSMS? Should I create a query each time I want to do so?
Use SQL Server Management Studio On the Table Designer menu, select Indexes/Keys. In the Indexes/Keys dialog box, select Add. In the grid under General, select Type and choose Unique Key from the drop-down list box to the right of the property, and then select Close.
A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table. You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate values.
SQL UNIQUE constraint for 2 columns example Notice that we named the UNIQUE constraints using CONSTRAINT keyword. We can use this name to remove the UNIQUE constraint later if we want. To define a UNIQUE on multiple columns, we put a comma-separated columns list inside parenthesis that follows the UNIQUE keyword.
You can define a UNIQUE constraint at the column or the table level. Only at the table level, you can define a UNIQUE constraint across multiple columns. Once a UNIQUE constraint is defined, if you attempt to insert or update a value that already exists in the column, SQLite will issue an error and abort the operation.
You were almost there. If you use the constraint
keyword you need to provide a name.
ALTER TABLE Attendance ADD CONSTRAINT UQ_TagID_SessionID UNIQUE NONCLUSTERED
(
TagID,
SessionID
)
Or alternatively
ALTER TABLE Attendance ADD UNIQUE NONCLUSTERED
(
TagID,
SessionID
)
also works but then the constraint is auto named
If you prefer to do it via GUI instead of via ALTER
statements, you can also right-click on the table in Object Explorer, select Design
, then right-click somewhere on the empty background, and select Indexes/Keys
. This will open a dialog where you select "Unique key" as the type.
Doing changes via GUI is a fast way for actions you tend to do rarely and hence are not sure about the syntax.
Many Management Studio dialogs - but not this one, probably as it is a sub dialog of the table designer dialog - have a "Script" button on the top left, which writes the action you are configuring via GUI to a query window so that you can save them for future similar tasks, or a copy and paste them, should you need similar actions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With