简体   繁体   English

如果未提供列列表,则对具有RowVersion列的表执行INSERT操作需要一个空值。 为什么?

[英]Doing INSERT on table with RowVersion column requires a null value if column list is not provided. Why?

Working a project where we're considering adding a rowversion column to a bunch of tables. 在一个我们正在考虑将rowversion列添加到一堆表的项目中。 Seems like it wouldn't be a big deal because SQL Server assigns the value, so we wouldn't need to modify existing stored procedures, of which there are many. 似乎没什么大不了的,因为SQL Server分配了该值,所以我们不需要修改现有的存储过程,其中有很多存储过程。 Not that easy, though, because the INSERT requires either a column list or a null value. 但是,这并不容易,因为INSERT需要列列表或空值。 So if a rowversion column were added to a table, any stored procedure written without the column list would fail. 因此,如果将rowversion列添加到表中,则没有该列列表的任何存储过程都将失败。

Below is sample code from the Microsoft docs with some modifications to show what I mean: 以下是Microsoft文档中的示例代码,进行了一些修改以显示我的意思:

CREATE TABLE MyTest   
(
     myKey int PRIMARY KEY,
     myValue int, 
     RV rowversion
);  
GO  

--Works fine 
INSERT INTO MyTest (myKey, myValue) VALUES (1, 0);  
GO  

--Fails with error: Column name or number of supplied values does not match 
--table definition
INSERT INTO MyTest VALUES (2, 0); 

--Works fine. Weird
INSERT INTO MyTest VALUES (2, 0, NULL);
GO  

I don't understand why it requires a NULL value if a column list isn't supplied. 我不明白,如果没有提供列列表,为什么它需要NULL值。 Since SQL Server calculates the value, I don't see why it would throw off the mapping to the table definition, and it makes the code confusing because it looks as if you're giving the field a null value when that's not what happens. 由于SQL Server计算该值,所以我不明白为什么它会抛弃到表定义的映射,并且使代码令人困惑,因为看起来好像您在给该字段提供null值(如果未发生这种情况)。

Does anybody know the reason for this peculiar behavior? 有人知道这种奇怪行为的原因吗?

The column-order is only predefined, when you provide all values. 当您提供所有值时,列顺序仅是预定义的。 Otherwise you could also provide the Parameters in the wrong order. 否则,您也可能以错误的顺序提供参数。 So if you want the to skip Parameters, you have to provide a Columnlist, to give a hint, how the values should be interpreted, wether there is a computed value involved, or not. 因此,如果要跳过参数,则必须提供一个Columnlist,以提示如何解释值,是否涉及计算值。

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

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