运用Merge Into实现增加或更新数据

本文介绍了一个使用 SQL 的 Merge 语句来更新或插入数据到 [Categories] 表的具体示例。通过定义 @SqlStr 变量并设置其为包含 Merge 语句的 N 字符串,实现了当 CategoryID 存在时更新对应记录,不存在时插入新记录的功能。
  declare @SqlStr as nvarchar(max)
  set @SqlStr=N'Merge Into [Categories] t 
  USING(VALUES (9,''rice'',''main food'',null))
  AS s ([CategoryID],[CategoryName],[Description],[Picture])
  on t.[CategoryID]=s.[CategoryID]
  When Matched Then Update Set t.[CategoryName]=s.[CategoryName],
                               t.[Description]=s.[Description],
                               t.[Picture]=s.[Picture]
  When Not Matched Then Insert ([CategoryName],[Description],[Picture])
                        values(s.[CategoryName],s.[Description],s.[Picture]);'
  exec sp_executesql @SqlStr 
View Code


运行截图:

转载于:https://www.cnblogs.com/527289276qq/p/4635546.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值