[英]Identity key on varchar column - T-SQL
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. 我想知道我是否可以创建一个Identity(在Varchar列上自动增加。我如何使它成为主键并在其他表上创建外键引用。
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)? 有没有办法可以将QuestionNo作为主键并在另一个表中引用它(比如Answers(AnswerID,QuestionNo,AnswerText)?
This worked for me on SQL Server 2005: 这在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... 主要部分是计算列需要PERSISTED关键字......
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)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.