首页 > 解决方案 > 在插入新行时结转列值

问题描述

我有一个SQL Server包含以下列的表格:

Item Eng1 Eng2  Eng3 UpdatedDate UpdatedBy

表中的当前条目是:

item1  jacob  john  null  1/1/2000  Sheila123@gmail.com
item2  alex   null  null  2/1/2000  clint123@gmail.com

现在,假设item1要在其中插入另一个条目Eng2=gregEng3=tom因此Eng1=jacob必须结转。因此条目现在应该是:

 item1  jacob  john  null  1/1/2000  Sheila123@gmail.com
 item2  alex   null  null  2/1/2000  clint123@gmail.com
 item1  jacob  greg  tom   2/10/2000 sally123@gmail.com

因此,如果与新数据条目不同,则基本上替换列值,否则将继续存在的最新列值

标签: sqlsql-servertsql

解决方案


您可以找到前 1 个匹配项,并插入新记录以替换现有记录的空值。

于 2020 年 9 月 22 日更新。包括全新记录的插入

declare @eng1 varchar(255),
        @eng2 varchar(255) = 'greg',
        @eng3 varchar(255) = 'tom',
        @item varchar(255) = 'item1',
        @updatedDate date = '2/10/2000',
        @updatedBy varchar(255) = 'sally123@gmail.com'

Insert into yourTable (Item, Eng1, Eng2, Eng3, UpdatedDate, UpdatedBy)
select top 1    Item,
                isnull(@eng1, Eng1),
                isnull(@eng2, Eng2) ,
                isnull(@eng3, Eng3),
                UpdatedDate = @updatedDate,
                @updatedBy  
from yourTable
where Item = @item
Union
Select  @item,
        @eng1,
        @eng2,
        @eng3,
        UpdatedDate = @updatedDate,
        @updatedBy
From yourTable
where not exists (Select 1 From yourTable where Item = @item) --For entirely new records
order by UpdatedDate desc

推荐阅读