如何在update语句中解决select结果的开窗函数

weixin_52728846 2021-06-30 10:45:12

这是我的select 语句

select '402'+right('00000' + (cast((row_number() over ( order by getdate())) as varchar(6))),4) as 新商品编号,* 
from 商品表a
join  商品表b on a.id=b.id
where b.商品类别='112'

select 的结果已经达到我要结果,就是把商品表a中的旧商品编号替换成新的商品编号(按402+0001开始递升)

我的目的是想能够这样update这个select结果

update a set 商品编号= '402'+right('00000' + (cast((row_number() over ( order by getdate())) as varchar(6))),4)
from商品表a
join  商品表b on a.id=b.id
where b.商品类别='112'

但是结果提示:开窗函数只能出现在 SELECT 或 ORDER BY 子句中。

还请请求各位大神指导一二,谢谢了!

 

...全文
705 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuzuning 2021-07-01
  • 打赏
  • 举报
回复

开窗函数太新,已超出我的知识范围,我只知道如果使用当前表字段加工而城的数据修改表字段,是违规的。因为极易出现死循环,至少需要一个自联接,伪装成两个表来骗过 sql 的语法检查

weixin_52728846 2021-06-30
  • 打赏
  • 举报
回复

好像举例的和我表达不太一样呢,还不是很明白

IEEE_China 2021-06-30
精选
  • 举报
回复
@weixin_52728846 无论你select语句怎么写的,放到cte里,update更新数据 from cte where 条件 ,有那么难吗
IEEE_China 2021-06-30
  • 打赏
  • 举报
回复

示例



declare @dta as table(
    姓名 nvarchar(10),
    性别 nvarchar(10)
)

declare @dtb as table(
    性别 nvarchar(10),
    数量 int
)

insert into @dta(姓名,性别)
select '张三','男' union all 
select '赵二','男' union all 
select '王五','男' union all 
select '周六','女' 

insert @dtb (性别,数量)
select '男',0 union all
select '女',0

---    查看
select * from @dta
select * from @dtb 

---    更新
;with cte(sex,cnt) as(
    select 性别,COUNT(1) from @dta group by 性别
)
update @dtb set 数量=cnt  from cte as c where 性别=c.sex

---    查看
select * from @dtb 

结果


(4 行受影响)

(2 行受影响)
姓名         性别
---------- ----------
张三         
赵二         
王五         
周六         

(4 行受影响)

性别         数量
---------- -----------
          0
          0

(2 行受影响)

(2 行受影响)

性别         数量
---------- -----------
          3
          1

(2 行受影响)

IEEE_China 2021-06-30
  • 打赏
  • 举报
回复

使用 WITH common_table_expression 子句 参考文档 https://docs.microsoft.com/zh-cn/sql/t-sql/queries/update-transact-sql?redirectedfrom=MSDN&view=sql-server-ver15 with cte as( select 语句 ) update 语句

weixin_52728846 2021-06-30
  • 举报
回复
@IEEE_China 可以深入一点么,初学自学者有点吃力

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧