处理“Insert Into TABLE Values()”中的标识列 陈述?
在 SQL Server 2000 或更高版本中,使用如下语句时是否可以处理自动生成的主键(身份)列?
Insert Into TableName Values(?, ?, ?)
我的目标是根本不使用列名称。
In SQL Server 2000 or above is there anyway to handle an auto generated primary key (identity) column when using a statement like the following?
Insert Into TableName Values(?, ?, ?)
My goal is to NOT use the column names at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
默认情况下,如果您有标识列,则不需要在 VALUES 部分中指定它。 如果您的表是:
那么您可以这样做:
这将为您自动生成 ID,您根本不必考虑它。 如果您
SET IDENTITY_INSERT MyTbl ON
,则可以为 ID 列分配一个值。By default, if you have an identity column, you do not need to specify it in the VALUES section. If your table is:
Then you can do:
This will auto-generate the ID for you, and you don't have to think about it at all. If you
SET IDENTITY_INSERT MyTbl ON
, you can assign a value to the ID column.生成列列表的另一个“技巧”是将“列”节点从对象资源管理器拖到查询窗口上。
Another "trick" for generating the column list is simply to drag the "Columns" node from Object Explorer onto a query window.
最佳实践是显式列出列:
否则,如果向表中添加另一列,原始插入将会中断。
The best practice is to explicitly list the columns:
Otherwise, your original insert will break if you add another column to your table.
您有 2 个选择:
1) 指定列名称列表(不带标识列)。
2) SET IDENTITY_INSERT tablename ON,后跟为标识列提供显式值的插入语句,后跟 SET IDENTITY_INSERT tablename OFF。
如果您避免使用列名称列表,也许这个“技巧”可能会有所帮助?:
You have 2 choices:
1) Either specify the column name list (without the identity column).
2) SET IDENTITY_INSERT tablename ON, followed by insert statements that provide explicit values for the identity column, followed by SET IDENTITY_INSERT tablename OFF.
If you are avoiding a column name list, perhaps this 'trick' might help?:
由于将代码放在注释中是不切实际的,因此响应您在 Eric 的回答中的评论,即它不适合您...
我刚刚使用默认设置在 SQL 2005 框上运行了以下内容(抱歉,没有 2000 方便)它工作正常,没有错误:
您是否可能在值列表中发送 ID 值? 如果您实际上为其传递了一个值,我认为您不能让它忽略该列。 例如,如果您的表有 6 列,并且您想忽略 IDENTITY 列,则只能传递 5 个值。
Since it isn't practical to put code in a comment, in response to your comment in Eric's answer that it's not working for you...
I just ran the following on a SQL 2005 box (sorry, no 2000 handy) with default settings and it worked without error:
Are you perhaps sending the ID value over in your values list? I don't think that you can make it ignore the column if you actually pass a value for it. For example, if your table has 6 columns and you want to ignore the IDENTITY column you can only pass 5 values.
其中“customer”是表名
where 'customer' is table name