【问题标题】:SQL INSERT INTO TABLE with dynamic and static column values具有动态和静态列值的 SQL INSERT INTO TABLE
【发布时间】:2021-04-12 20:26:46
【问题描述】:

称为“代码类型”的目标表:

contractid termid code1 code2 code3 createid createdate updateid lastupdate
contractid1 termid1 static# static# A staticname getdate() staticname getdate ()
contractid1 termid1 static# static# B staticname getdate() staticname getdate ()
contractid2 termid2 static# static# A staticname getdate() staticname getdate ()
contractid2 termid2 static# static# B staticname getdate() staticname getdate ()

你好!使用 SSMS 17。

好的,所以我正在努力有效地实现一个查询,它将将行插入到上面的表格式中,但基于连接的数据,以根据其他两个表的条​​件动态更改 contractid 和 termid;以及从 code3 的 20 个选项的已知列表中插入值。

将通过基于 contract_name 的 where 条件从“contract”表中找到 ContractID。 contract_name 只存在于这个“合同”表中。

TermID 将通过基于 term_name 的 where 条件找到,并且必须链接到上面的 contractID。 TermID 和 term_name 只存在于“term”表中,在contractID上链接到“contract”

对于这两个值,简单的选择将是:

select c.contractid, t.termid
from contract c
left join term t on t.contractid = c.contractid and t.term_name like 'term name%'
where c.contract_name like 'contract name%'

code1 和 code2 是已知值。 code3 有 20 个值,每个值都需要插入到这个“代码类型”表中,它们都是数字和字母字符(不是 all A-Z,1-0,而是一个只有 20 个的较小列表)。重申,contractid1 中的 termid1 需要为所有离散的 20 个 code3 值(A、B、C...Z、1、2...0)输入行,其中静态字段是已知的,但 contractid 和 termid 是动态的根据上述条件插入。其余的值也是已知的静态值或 getdate()。

第 4 个表中存在 20 个不同的代码,我们将其称为“code3values”,因此我认为可以在解决方案中从该表中提取它们以循环通过 code3 输入。

我通常会做的是将上述选择导出到 Excel 中,然后为每种可能性手动创建一个“插入”行,例如非常无聊:

insert into codetypes values('contractid1','termid1','1','2','A','myname',getdate(),'myname',getdate())
insert into codetypes values('contractid1','termid1','1','2','B','myname',getdate(),'myname',getdate())

这次数据太大了,想学一个更高效/更有创意的方法。

我认为下面是一个不错的开始,但我仍然需要一种方法来循环浏览 20 个 code3 值选项。

insert into codetypes
(contractid, termid, code1, code2, code3, createid, createdate, updateid, lastupdate)

select c.contractid, t.termid, '1','2','A','name',getdate(),'name',getdate()
from term t
left join contract c on c.contractid = t.contractid
where t.term_name like 'term name%'
and c.contract_name like 'contract name%'

【问题讨论】:

  • 如果您想要真正的 LEFT JOIN 结果,请将 t.term_name 条件从 WHERE 移至 ON。就像现在一样,您会得到常规的 INNER JOIN 结果。

标签: sql sql-insert


【解决方案1】:

我在发帖之前没有花足够的时间,但这是我想出的答案:

insert into codetypes
    (contractid, termid, code1, code2, code3, createid, createdate, updateid, lastupdate)
select
    c.contractid, t.termid, '1', '2', f.code3, 'name', getdate(), 'name', getdate()
from contract c
    left join term t on t.contractid = c.contractid
    join code3values f on f.code3 != ''
where c.contract_name like 'contract name%'
    and t.term_name like 'term name%'

【讨论】:

    猜你喜欢
    • 2023-02-09
    • 2019-11-07
    • 2010-10-26
    • 2014-08-16
    • 1970-01-01
    • 2014-05-12
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    相关资源
    最近更新 更多