Welcome to OStack Knowledge Sharing 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...