简体   繁体   English

如果列中存在值,则插入新行

[英]Insert new row if value present in column

I need to check if a column value exists for a record, and if so insert a duplicate of that record, with one of the fields updated. 我需要检查记录是否存在列值,如果存在,则插入该记录的副本,并更新其中一个字段。

The fields for my IncCodes table are are chars: 我的IncCodes表的字段是字符:

IncomeCode,
Description,
Location,
CostCentre,
NewIncomeCode

I already have an SQL command which updates all of the IncomeCodes from the NewIncomeCode and clears the NewIncomeCode column where present: 我已经有一个SQL命令来更新NewIncomeCode中的所有IncomeCodes并清除NewIncomeCode列所在的位置:

UPDATE IncCodes 
SET IncomeCode = NewIncomeCode
   ,NewIncomeCode = ''
WHERE NewIncomeCode <> ''
  AND Location = Location1

However I need command which does the same thing except instead of updating the IncomeCode field, creates a duplicate record with the IncomeCode updated by the NewIncomeCode field. 但是我需要执行相同操作的命令,除了不更新IncomeCode字段,使用NewIncomeCode字段更新的IncomeCode创建重复记录。 Something like this pseudo sql: 像这样的伪sql:

INSERT INTO IncCodes
VALUES (SELECT NewIncomeCode
              ,Description
              ,Location
              ,CostCentre
              ,NULL
        FROM IncCodes
        WHERE NewIncomeCode <> '')

Any advice much appreciated. 任何建议都非常感谢。 I can see similar questions about insert based on criteria but nothing specifically what I need. 我可以根据标准看到关于插入的类似问题,但没有具体说明我需要什么。

Thanks in advance. 提前致谢。

INSERT INTO IncCodes (IncomeCode,Description,Location,CostCentre,NewIncomeCode)
SELECT NewIncomeCode
              ,Description
              ,Location
              ,CostCentre
              ,NULL
        FROM IncCodes
        WHERE NewIncomeCode <> ''

Never write an insert without specifying the columsn that is a SQL antipattern and can cause lots of data integrity problems. 切勿在未指定作为SQL反模式的columsn的情况下编写插入,并且可能导致大量数据完整性问题。

INSERT IGNORE INTO IncCodes
    (IncomeCode, Description, Location, CostCentre, NewIncomeCode)
SELECT
    NewIncomeCode, Description, Location, CostCentre, ''
FROM IncCodes
WHERE NewIncomeCode <> '' AND Location = Location1
;

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

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