How do I make a composite key with SQL Server Management Studio?

SqlSql ServerTsqlSsmsKey

Sql Problem Overview


How do I make a composite key with SQL Server Management Studio?

I want two INT columns to form the identity (unique) for a table

Sql Solutions


Solution 1 - Sql

enter image description here

  1. Open the design table tab
  2. Highlight your two INT fields (Ctrl/Shift+click on the grey blocks in the very first column)
  3. Right click -> Set primary key

Solution 2 - Sql

here is some code to do it:

-- Sample Table
create table myTable 
(
    Column1 int not null,
    Column2 int not null
)
GO

-- Add Constraint
ALTER TABLE myTable
    ADD CONSTRAINT pk_myConstraint PRIMARY KEY (Column1,Column2)
GO

I added the constraint as a separate statement because I presume your table has already been created.

Solution 3 - Sql

create table my_table (
    id_part1 int not null,
    id_part2 int not null,
    primary key (id_part1, id_part2)
)

Solution 4 - Sql

In design mode (right click table select modify) highlight both columns right click and choose set primary key

Solution 5 - Sql

Open up the table designer in SQL Server Management Studio (right-click table and select 'Design')

Holding down the Ctrl key highlight two or more columns in the left hand table margin

Hit the little 'Key' on the standard menu bar at the top

You're done..

:-)

Solution 6 - Sql

create table myTable 
(
    Column1 int not null,
    Column2 int not null
)
GO


ALTER TABLE myTable
    ADD  PRIMARY KEY (Column1,Column2)
GO

Solution 7 - Sql

Highlight both rows in the table design view and click on the key icon, they will now be a composite primary key.

I'm not sure of your question, but only one column per table may be an IDENTITY column, not both.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmrblahView Question on Stackoverflow
Solution 1 - SqlCoryView Answer on Stackoverflow
Solution 2 - SqlRoatin MarthView Answer on Stackoverflow
Solution 3 - SqlyfeldblumView Answer on Stackoverflow
Solution 4 - SqlGratzyView Answer on Stackoverflow
Solution 5 - Sqluser4878037View Answer on Stackoverflow
Solution 6 - SqlTejasView Answer on Stackoverflow
Solution 7 - SqlKM.View Answer on Stackoverflow