简体   繁体   English

使用默认值将新列添加到现有表

[英]Adding new column to existing table with default value

Suppose I have a table called SerialNumbers which has columns: 假设我有一个名为SerialNumbers的表,该表具有以下列:

  • Id (int) ID (int)
  • SerialNumber (nvarchar) 序列号(nvarchar)
  • IsValid (bit) IsValid (bit)
  • ToBeUsedBy (DateTime) ToBeUsedBy (DateTime)

Currently this table is being used by numerous different applications. 当前,该表被许多不同的应用程序使用。 Now we have a requirement to add a new column named CurrentlyAt (int) which will always have a default value of 1 . 现在,我们需要添加一个名为CurrentlyAt (int)的新列,该列将始终具有默认值1 I have gone ahead and added the column with a default value of 1 . 我继续并添加了默认值1的列。

So my question is, would I now have to change all my previous insert queries to include the new column or would it add a value by default if I didn't add it to the old insert statements? 所以我的问题是,我现在是否必须更改所有以前的insert查询以包括新列,或者如果不将其添加到旧的insert语句中,则默认情况下会添加一个值?

The answer, of course, is that it depends. 答案当然取决于它。

As long as your existing INSERT statements have an explicit column list, you don't need to edit them, and the default value will be inserted, well, by default. 只要您现有的INSERT语句具有显式的列列表,就无需对其进行编辑,并且默认情况下将插入默认值。

INSERT INTO SerialNumbers (
  Id,
  SerialNumber,
  IsValid,
  ToBeUsedBy)
SELECT....

BUT if you have any inserts that do not have a column list, they'll throw an error: 但是,如果您有任何没有列列表的插入,它们将引发错误:

INSERT INTO SerialNumbers 
SELECT....

Because the number of columns in the SELECT , or VALUES clause perhaps, will no longer match the number of columns in the INSERT target table. 因为SELECTVALUES子句中的列数可能不再与INSERT目标表中的列数匹配。

The solution there is to add the explicit column list, and then to get in the habit of always using said list, for this very reason. 出于这个原因,解决方案是添加显式列列表,然后养成始终使用所述列表的习惯。

EDIT: To Sean Lange's point, I was assuming the new column was NOT NULL . 编辑:肖恩·兰格的观点,我假设新列NOT NULL If it's nullable, then yes, there are more possible outcomes, which are likely to generate outcomes that are not as expected. 如果它可以为空,则是,会有更多可能的结果,这些结果可能会产生与预期不同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM