如何使用select的结果在update语句中

这是我的select语句:
select  convert(numeric(10,2),sum(金额)) as 总金额 from 处方表 where 住院号='20191223001') where 住院号='20191223001'
然后我的目的是想能够这样
update 账单表 set 总金额=(select的结果) where 住院号='20191223001'

sql语句中declare一个变量,类似:select 变量=convert(numeric(10,2),sum(金额))  from xx ,然后set赋值即可。

2个方法,
1 设置一个 变量  
declare @num;
select  @num=convert(numeric(10,2),sum(金额)) as 总金额 from 处方表 where 住院号='20191223001') where 住院号='20191223001'

update 表 xxx=@num  where ......

第二个方法,就是sql语句直接放到 update
update 表 xxx=(select ...........)  where ......

用with 也可以

SQL就那么几条语句用多了就自然熟悉了,驾轻就熟,游刃有余,读书多遍其意自现等等先贤名言.
把SQL语句写成一个类文件,然后拼接各种语句传递去执行就是.

update tablename set columnname=(select top 1 columnname2 from tablenam2)

update a set a.column=b.column
from tablename1 as  a,tablename2 as b
where a.primarykey=b.primarykey

可以放在一起写,但是select只能有一行数据返回,还要对应的数据类型要能转换才行

附上代码
declare @num float
select  convert(numeric(10,2),sum(金额))  from 处方表 where 住院号='201912230001'
update 账单表 set 总金额=@num where 住院号='201912230001'

update 账单表 set 总金额=(select  convert(numeric(10,2),sum(金额))  from 处方表 where 住院号='201912230001')where 住院号='201912230001'

刚刚运行成功了 第一种方法是我没将select的结果赋值给@num第二种方法 刚刚也成功了 不过我忘了之前是哪里小蜜蜂论坛回帖机出了错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值