views:

86

answers:

2

Hi there. I want to know if I can create an Identity (auto increment on a Varchar column. and how can I make it a primary key and create foreign key references on other table.

This is the code i have -

CREATE TABLE Questions(
    QuestionID int IDENTITY PRIMARY KEY, 
    QuestionNo as 'Q'+Cast(QuestionID as Varchar(10),       
    Question Varchar(200)
)

Is there a way I can make QuestionNo as Primary key and reference it in another table (say Answers (AnswerID, QuestionNo, AnswerText)?

+4  A: 

This worked for me on SQL Server 2005:

CREATE TABLE Questions(
  QuestionID int IDENTITY NOT NULL, 
  QuestionNo as 'Q'+Cast(QuestionID as Varchar(10)) PERSISTED PRIMARY KEY, 
  Question Varchar(200)
)

The main part is that a computed column needs the PERSISTED keyword...

OMG Ponies
Thank You worked for me too. :)
Abey
But how would you refer this in another table as a foreign key?I get Error from thisCREATE TABLE Answers(AnswerID int IDENTITY PRIMARY KEY, QuestionNo Varchar(10), Answer nvarchar(200), Foreign key (QuestionNo) references Questions(QuestionNo))
Abey
OMG Ponies
+3  A: 

Not directly.

  • use a computed column on an integer column (as per OMG Ponies answer)
  • use a udf (SO1, SO2)

My question is: why? it will be slower than a straightforward number.

gbn
Just wanted the identity key to be more descriptive like Q1, Q2 rather than plan numbers
Abey