开发者

Identity key on varchar column - T-SQL

开发者 https://www.devze.com 2023-01-14 04:03 出处:网络
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.

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),       
    Q开发者_运维百科uestion Varchar(200)
)

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


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...


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.


this code is working

CREATE TABLE IdentityExample(
  ID int IDENTITY NOT NULL, 
  QNo as 'Q'+Cast(ID as Varchar(10)) PERSISTED PRIMARY KEY, 
  name Varchar(200)
)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号