Anjola
Anjola

Reputation: 347

How to set a primary key using SQL

I have this table 'Cars', attributes:

MODEL nvarchar(20)
STYLE nvarchar(20)
ENGINE nvarchar(5)
CAPACITY smallint
MAX_SPEED smallint
PRICE smallmoney
MARKET nvarchar(20)
COMPETITOR nvarchar(20)

I would like to set 'PRICE' as the primary key via a SQL sStatement, so I've tried:

ALTER TABLE Cars
ADD PRIMARY KEY (PRICE)

But I just get the error

The ALTER TABLE SQL construct or statement is not supported.

in Visual Studio 2010.

Upvotes: 1

Views: 527

Answers (2)

sovemp
sovemp

Reputation: 1413

As has been said above, price is a bad primary key. But ... the correct syntax to do what you are trying to do is:

ALTER TABLE Cars
ADD CONSTRAINT cars_pk PRIMARY KEY (PRICE)

Upvotes: 1

Dan Bracuk
Dan Bracuk

Reputation: 20804

Visual studio is not a database client. If you want to run any query at all, you have to use a client that allows you to do so. The details depend on the database engine you are using.

If you want to do this with Visual Studio, you have to send that command, as a query, the same way you would send a select query. Once again, the details depend on your database engine.

Something else that depends on the database engine is the syntax of the command itself. Some will allow what you tried. Other will make you use the constraint keyword.

Finally, as mentioned in the comments, price is a poor choice for the primary key. Better choices would be a uuid, an autoincrementing integer, or, the VIN.

Upvotes: 0

Related Questions