Solved

SQL Server Management Studio - Create Primary Key From 2 Columns

Posted on 2014-11-09
3
125 Views
Last Modified: 2014-11-09
Hi

I have a SQL Table that contains two nvarchar columns called "Article" and "Site".
I have to create a primary Key that contains both of these. How would I do this in SQL
Server Management Studio
0
Comment
Question by:murbro
  • 2
3 Comments
 
LVL 65

Accepted Solution

by:
Jim Horn earned 500 total points
Comment Utility
When creating the table...
CREATE TABLE your_table_name (
  Article nvarchar(50), 
  Site nvarchar(50), 
  CONSTRAINT pk_your_table_name PRIMARY KEY (Article, Site) 
GO

Open in new window


.. and if the table already exists..
ALTER TABLE your_table_name
ADD CONSTRAINT pk_your_table_name PRIMARY KEY (Article, Site) 
GO

Open in new window


Side comments:

1.

Better to use numeric values instead of char's, as the size of the columns in a primary key equates to faster querying, and char values (50x2 in this example) will be much better then say integers (4x2)

2.

In both examples I included the name pk_your_table_name, which is a best practice.  

Say you have three environments such as DEV, TEST, PROD, and the pk wasn't named.  If you ever had to alter the PK, if a name is not provided the system generates a name, so you'd have three different names to deal with when promoting code.
0
 

Author Closing Comment

by:murbro
Comment Utility
Great answer. Thanks very much
0
 
LVL 65

Expert Comment

by:Jim Horn
Comment Utility
Thanks for the grade.  Good luck with your project.  -Jim
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now