SQL 將2張不相關的表拼接成2列,批量更新至另一張表


update SO_Master set LotteryNo=t2.LotteryNo,UpdateTime=GETDATE() 
--select sm.LotteryNo,sm.SysNo,t2.LotteryNo
from SO_Master sm
inner join (			
	select 
	SysNo,ROW_NUMBER() over(order by sysno asc) rIndex
	from SO_Master 
	where WebSiteSysNo =6 and SOAmt >=800 and LotteryNo is null  AND OrderDate >='2016/09/22 00:00:00' and OrderDate<'2016/09/24 00:00:00' and Status not in(-1,-2,-3)
) t1 on t1.SysNo=sm.SysNo
inner join (
	select 
	LotteryNo,ROW_NUMBER() over(order by sysno asc) rIndex
	from SO_Master_Lottery
	 where  status=0 and WebSiteSysNo = 6
) t2 on t1.rIndex=t2.rIndex
where sm.SysNo=1422087 and sm.LotteryNo is null
--order by t1.SysNo asc,t2.LotteryNo asc

SO_master表簡稱SO,SO_Master_Lottery表簡稱SML,

1.首先將SO表列查詢出來作為更新條件,然后使用Row_Number排序獲得序列

2.將SML表列查詢出來作為更新值,然后使用Row_number排序獲得序列

3.通過序列號將SO表和SML表關聯起來,獲得所需的更新條件和更新值,如下代碼:

select sm.LotteryNo,sm.SysNo,t2.LotteryNo
from SO_Master sm
inner join (			
	select 
	SysNo,ROW_NUMBER() over(order by sysno asc) rIndex
	from SO_Master 
	where WebSiteSysNo =6 and SOAmt >=800 and LotteryNo is null  AND OrderDate >='2016/09/22 00:00:00' and OrderDate<'2016/09/24 00:00:00' and Status not in(-1,-2,-3)
) t1 on t1.SysNo=sm.SysNo
inner join (
	select 
	LotteryNo,ROW_NUMBER() over(order by sysno asc) rIndex
	from SO_Master_Lottery
	 where  status=0 and WebSiteSysNo = 6
) t2 on t1.rIndex=t2.rIndex
where sm.SysNo=1422087 and sm.LotteryNo is null
order by t1.SysNo asc,t2.LotteryNo asc

4.使用批量更新的SQL執行語法,進行內連接,由更新主表SO_master表關聯t1更新條件表,然后內鏈接t2獲得更新值,t1和更新主表SO_master通過外鍵關聯,t2是根據t1的序號關聯t2的,然后加上所有查詢條件,

主要是帶上更新值的列LotteryNo

 

 

其他sql介紹:

下面這個Sql是按照Row_number更新數據的,僅供參考

update SO_Master set LotteryNo =t1.LotteryNo,UpdateTime=GETDATE() from SO_Master sm
inner join(
select SysNo, 168799-ROW_NUMBER()over(order by sysno asc) LotteryNo from SO_Master 
where WebSiteSysNo =6 and SOAmt >=800 and LotteryNo is null AND OrderDate >='2016/09/22 00:00:00' and OrderDate<'2016/09/24 00:00:00' and Status not in(-1,-2,-3)
) t1 on sm.SysNo=t1.SysNo
where sm.LotteryNo is null

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM