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
470 views
in Technique[技术] by (71.8m points)

sql - How to alter and add a datetime2(7) not null field to an already existing table with data?

I have table that already has a set of values. Now I have to add a column thats of type datetime2(7) which will be not null. I cannot insert getdate() as the default value as this can lead to problems. How can I add that column with 0001-01-01 00:00:00.0000000 as the default value?

question from:https://stackoverflow.com/questions/65842524/how-to-alter-and-add-a-datetime27-not-null-field-to-an-already-existing-table

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

1 Reply

0 votes
by (71.8m points)

Define the DEFAULT value and use WITH VALUES:

ALTER TABLE dbo.YourTable ADD NewColumn datetime2(7) NOT NULL DEFAULT '0001-01-01T00:00:00.0000000' WITH VALUES;

Though, a default value of 0001-01-01T00:00:00.0000000 is pretty odd. Seems like, in my opinion, it should be NULL. NULL means an unknown value, and clearly you don't know what the value of these rows should be.


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

...