【问题标题】:updating a column in a table having duplicate rows更新具有重复行的表中的列
【发布时间】:2012-09-20 15:53:19
【问题描述】:

在更新具有重复行的表中的列时遇到问题。 我有一个表“tab1”,它的数据看起来像这样..

标识 col2 col3 col4 col5 col6 col7 1 xim M gtt tif 1 2 2 白色 M abc png 0 25 2 白色 M abc jpeg 0 25 3 gtc V ftt gif 4 72

此表包含重复的 Id,但仅在 col5 中有所不同。 该表包含大约 4000 行 我想更新 col5 使输出看起来像这样..

标识 col2 col3 col4 col5 col6 col7 1 xim M gtt tif 1 2 2 白色 M abc png,jpeg 0 25 3 gtc V ftt gif 4 72

有没有办法使用更新语句来更新这个表,我是否必须为此更新创建一个临时表..??

【问题讨论】:

  • 您如何确定应该是png,jpeg 而不是jpeg,png
  • 您正在对数据库进行非规范化。不要这样做。
  • 嗯,将一个非规范化的坏设计换成另一个坏的多值列。 Id 应该是 (4?) 并且如果需要添加另一个列来指示一个组,或者更好地使用另一个表来规范化设计。
  • @ruakh.. 一切都很好,只要数据不丢失
  • 不仅是 "," 任何分隔符都可以像 "|"等等。

标签: sql


【解决方案1】:

我同意 njk 和 Tony 发布的 cmets。对数据库进行非规范化不是一个好主意,但也许您的最终目标不是那么明显,并且组合图像扩展名适合您的特定需求。

这可以满足您的要求。我确信也有一种方法可以使用 XML 来完成,而无需在函数中使用光标...

use tempdb
go

create table tmp (
  id int, 
  col2 varchar(10), 
  col3 varchar(10), 
  col4 varchar(10), 
  col5 varchar(255), 
  col6 int, 
  col7 int
)
go

insert into tmp values
(1, 'xim', 'M', 'gtt', 'tif', 1, 2),
(2, 'white', 'M', 'abc', 'png', 0, 25),
(2, 'white', 'M', 'abc', 'jpeg', 0, 25),
(2, 'white', 'M', 'abc', 'gif', 0, 25),
(3, 'gtc', 'V', 'ftt', 'jpeg', 4, 72),
(3, 'gtc', 'V', 'ftt', 'tif', 4, 72),
(3, 'gtc', 'V', 'ftt', 'png', 4, 72),
(3, 'gtc', 'V', 'ftt', 'gif', 4, 72)
go

create function fnConcatCol5 (@id int) returns varchar(255) as
begin
  declare @rtn varchar(255) = '', @val varchar(10)

  declare cr cursor local for
    select col5 from tmp where id = @id

  open cr
  fetch next from cr into @val

  while @@fetch_status = 0
  begin
    set @rtn = @rtn + @val + ','
    fetch next from cr into @val
  end

  close cr
  deallocate cr

  set @rtn = left(@rtn, datalength(@rtn) - 1)

  return @rtn
end
go

-- it is more efficient to split up the 'distinct' and function call
-- into separate SQL statements so the function is only run *one* time
-- for each unique id

select distinct id, col2, col3, col4, col6, col7 
into #temp
from tmp

select id, col2, col3, col4, dbo.fnConcatCol5(id) as col5, col6, col7
from #temp
go

drop table tmp, #temp
go
drop function fnConcatCol5
go

返回的数据如下:

id    col2    col3    col4    col5                col6    col7
----- ------- ------- ------- ------------------- ------- ----
1     xim     M       gtt     tif                 1       2
2     white   M       abc     png,jpeg,gif        0       25
3     gtc     V       ftt     jpeg,tif,png,gif    4       72

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多