views:

38

answers:

3

Hi again,

I've got a script that generates a table - only my version of SQL 2008 throws up an error - has the syntax changed? Or how do I fix it manually?

CREATE TABLE ScoHistory (
    CourseID varchar (255) NOT NULL ,
    SessionID int NOT NULL ,
    ScoID varchar (255) NOT NULL ,
    StudentID varchar (255) NOT NULL ,
    DateRecorded datetime NULL ,
    score_raw varchar (12)  NULL,
    KEY student_course_sess_scohist_idx (StudentID, CourseID, SessionID, ScoID) -- this is the bit it doesn't like! It says incorrect syntax near KEY...
);

Many thanks in advance,

Spud

A: 

It would work like this, if this is the intended behaviour:

CREATE TABLE ScoHistory ( 
    CourseID varchar (255) NOT NULL , 
    SessionID int NOT NULL , 
    ScoID varchar (255) NOT NULL , 
    StudentID varchar (255) NOT NULL , 
    DateRecorded datetime NULL , 
    score_raw varchar (12)  NULL, 
    PRIMARY KEY (StudentID, CourseID, SessionID, ScoID) 
); 

It you would only like to create a non-unique index on the table, create the index using the CREATE INDEX statement.

treaschf
Okay - so what happens to 'student_course_sess_scohist_idx'? Have I missed something? : *
Spudhead
A: 
CREATE TABLE ScoHistory
  ( 
   CourseID varchar(255) NOT NULL
  ,SessionID int NOT NULL
  ,ScoID varchar(255) NOT NULL
  ,StudentID varchar(255) NOT NULL
  ,DateRecorded datetime NULL
  ,score_raw varchar(12) NULL,
  ) ;

ALTER TABLE dbo.ScoHistory ADD
CONSTRAINT PK_ScoHistory PRIMARY KEY (StudentID, CourseID, SessionID, ScoID);
Damir Sudarevic
Okay - so what happens to 'student_course_sess_scohist_idx'? Have I missed something? : *Will it affect anything if I follow your fix?
Spudhead
This will create index named `PK_ScoHistory`. Replace `PK_ScoHistory` with `student_course_sess_scohist_idx` if you like that name better. You can see index and key names in MSSMS (management studio) under `Tables/dbo.ScoHistory/Keys` and `Tables/dbo.ScoHistory/Indexes`
Damir Sudarevic
If you have code for database maintenance that rebuilds, reorganizes, drops or re-creates indexes (`ALTER INDEX ...`)than use your existing names. If not, than it is not that important, but it is a good thing to have some kind of recognizable index and constraint names when you get an error.
Damir Sudarevic
Okay - I'll give your fix a go and let you know! I'm still confused to be sure... Many thanks!
Spudhead
+1  A: 

You can define a named primary key table constraint like this:

CREATE TABLE ScoHistory (
CourseID varchar (255) NOT NULL,
SessionID int NOT NULL,
ScoID varchar (255) NOT NULL,
StudentID varchar (255) NOT NULL,
DateRecorded datetime NULL,
score_raw varchar (12) NULL,
CONSTRAINT student_course_sess_scohist_idx PRIMARY KEY (StudentID, CourseID, SessionID, ScoID) 
);
zinglon