【问题标题】:Insert multiple rows with hardcoded data, and one column from a multi-result select插入包含硬编码数据的多行,以及来自多结果选择的一列
【发布时间】:2016-11-23 09:44:34
【问题描述】:

我有以下两个表:UsersSettings
我想要做的是为每个现有用户的设置添加一行。所以在伪代码中:

foreach(NUMBER user_id IN Users){
  INSERT INTO "Settings" SET ("name", "value", "type", type_id, overridable)
                       VALUES ('date_format', 'dd-MM-yyyy', 'USER', user_id, '1');
}

如何在 SQL 中执行此操作?

Here at the Using INSERT with the VALUE Clause and a SELECT Subquery part我看到以下内容:

INSERT INTO MyTable (PriKey, Description)
   SELECT ForeignKey, Description
   FROM SomeView;

这几乎是我想要完成的,除了它从另一个表中获取所有插入值,而不是只有一个(在我的情况下为user_id)和其他“硬编码”。

编辑:我将 SQL 与 Oracle 数据库一起使用。

【问题讨论】:

  • @a_horse_with_no_name 添加它:SQL with Oracle DB。
  • 无关,但是:你真的应该避免那些可怕的带引号的标识符。
  • @a_horse_with_no_name 我完全同意,但不幸的是其他人制作了数据库,我和我团队中的其他人必须使用它。如果由我决定,我会选择其他数据库列这不是 SQL 关键字。我会和团队讨论这个问题,看看我们现在是否应该更改它。

标签: sql oracle select insert-into


【解决方案1】:

使用select .. insert 并在选择列表中提供常量:

INSERT INTO "Settings" ("name", "value", "type", type_id, overridable)
select 'date_format', 'dd-MM-yyyy', 'USER', user_id, '1'
from users;

【讨论】:

  • 谢谢!有效。比我想象的要容易得多。我会在 10 分钟内接受你的答复。
猜你喜欢
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
  • 1970-01-01
  • 2014-03-06
  • 2023-03-17
  • 2015-07-23
  • 2016-02-25
  • 1970-01-01
相关资源
最近更新 更多