Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

sql server - Is it possible to set a default value for field A based on the value of field B in the same table?

I have a table with an autonumber field. I have a second field where on insert I want it to take the generated number for the autonumber field and prefix it with 'S'. How can I do this? Can I put some kind of expression in the default value specification?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a (PERSISTED) computed column:

ALTER TABLE dbo.YourTable ADD PrefixedAutoNumber AS CONCAT('S',AutoNumber) PERSISTED;

Then you don't need to INSERT it, or anything else, it'll have simply have the value of your AutoNumber column prefixed with an 'S'. Persisting the column means you can add it to indexes, which'll help for performance if you'll going to be using the column for WHERE clauses or JOINs.

If it is, however, purely for display/presentation purposes, and will never be used in the WHERE/ON then you don't need to persist the column.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...