带主键和多插入速记身份
我想要一个简写(如果可能的话),用于将多个记录插入到具有主键和 IsIdentity 属性的表中。例如,假设我有一个名为“People”的表,其中包含以下列:
- ID(主键和身份[即自动增量])
- 姓名(不为空)
- Email (not null)
不包含自动递增 ID 列的插入语句是完全有效的,例如:
INSERT INTO People VALUES ('George', '[email protected]')
但是,如果我想在同一个语句中插入多个值,理想情况可以这样做,我不必显式指定列名称:
INSERT INTO People VALUES ( (auto, 'George', '[email protected]'), (auto, 'Mary', '[email protected]') )
我能找到的最好的解决方案是这样的:
INSERT INTO People ( SELECT 'George', '[email protected]', UNION ALL SELECT 'Mary', '[email protected]' )
我想你可能会说,这是一个有点无意义的追求,但我希望查询本身可以随着表设计而扩展。例如,如果列名称发生更改,或者添加了更多列,我不必在代码中的任何地方进行更改。
干杯:)
I would like a shorthand (if possible) for inserting multiple records into a table which has a primary key and IsIdentity property. For example, say I have a table called 'People' with the following columns:
- ID (Primary Key, and Identity [i.e. autoincrementing])
- Name (not null)
- Email (not null)
An insert statement excluding the auto-incrementing ID column is perfectly valid, such as:
INSERT INTO People VALUES ('George', '[email protected]')
But if I want to insert multiple values in the same statement, ideally that could be done something like this where I don't have to explicitly specify the column names:
INSERT INTO People VALUES ( (auto, 'George', '[email protected]'), (auto, 'Mary', '[email protected]') )
The best solution I could find was something like this:
INSERT INTO People ( SELECT 'George', '[email protected]', UNION ALL SELECT 'Mary', '[email protected]' )
I suppose you could argue, this is a somewhat meaningless pursuit, but I wanted the query itself to be extensible along with the table design. For example, if a column name changed, or more columns were added I wouldn't have to change this everywhere in the code.
Cheers :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像这样插入多行:
编辑:
只要您的主键设置为自动增量,您就可以将该字段置空,它会自动将值设置为自动增量值。
You can insert multiple rows like this:
EDIT:
As long as your primary key is set to auto increment, you can nullify the field and it will auto set the value to the auto increment value.
这取决于您使用的数据库。一些数据库允许多个值集:
That depends on what database you are using. Some databases allow multiple value sets: