views:

102

answers:

2

Hi!

I have a script of MySQL queries that I use and that work.

I'm trying to execute the same queries in Microsoft SQL server and there's one thing I don't understand.

MySql uses "key" to define a key made up of different fields.

What is the way to do the same thing in SQL Server?

Thanks!

-Adeena

+1  A: 

You can declare a primary key that consists of multiple columns in TSQL (SQL server's query language)

ALTER TABLE product
    ADD CONSTRAINT prim_prod PRIMARY KEY(product_foo, product_bar)

If you use SQL Server Management studio, you can also achieve this via "Modify Table".

recursive
hmm... I thought there could only be one primary key?
adeena
There is only one primary key, but it can consist of multiple columns. That way product_foo and product_bar needn't be unique on their own, but considered together they must be unique.I always prefer single field primary keys, but this is possible.
recursive
yes, only one primary key is allowed. But you can start with a table WITHOUT primary key.
splattne
This type of primary key is called a composite key, here is a nice blog post describing the various types of PK you could implement. http://weblogs.sqlteam.com/jeffs/archive/2007/08/23/composite_primary_keys.aspx
Almond
+1  A: 

In MySQL, the keyword KEY is simply a synonym for INDEX. The following two are equivalent:

CREATE TABLE foo (
  id     SERIAL PRIMARY KEY,
  ctime  DATETIME,
  KEY ctkey (ctime)
);

CREATE TABLE foo (
  id     SERIAL PRIMARY KEY,
  ctime  DATETIME,
  INDEX ctidx (ctime)
);

In Microsoft SQL Server, the closest equivalent is INDEX. As far as I can tell, to create an index on a column in Microsoft SQL Server, you use CREATE INDEX. You can also create constraints that build indexes as part of a CREATE TABLE statement, but if you just need an index, use CREATE INDEX.

CREATE TABLE foo (
  id     BIGINT IDENTITY PRIMARY KEY,
  ctime  DATETIME
);

CREATE INDEX ctidx ON foo(ctime);

See also documentation on CREATE INDEX.

Bill Karwin