----若#tab的行資料多時,或根據ID處理復雜邏輯多的時候,速度很慢。有高手能提供別的SQL邏輯寫法或者優化這種寫法么
if object_id('tempdb..#temp') is not null
begin
drop table #temp
end
if object_id('tempdb..#tab') is not null
begin
drop table #tab
end
create table #tab
(
col varchar(max),
col2 varchar(max),
col3 varchar(max),
col4 varchar(max)
)
---測驗新增模擬資料
insert into #tab(col,col2,col3,col4)values
('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),
('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),
('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),
('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),
('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),('A','A','A','A'),('A','A','A','A')
---
create table #temp
(
GetID uniqueidentifier,
col varchar(max),
col2 varchar(max),
col3 varchar(max),
col4 varchar(max)
)
insert into #temp select newID(),* from #tab
--核心邏輯
while Exists(select GetID from #temp where GetID is not null)
begin
declare @GetID uniqueidentifier='00000000-0000-0000-0000-000000000000'
select top 1 @GetID=GetID from #temp where GetID is not null
------此處為根據ID處理復雜邏輯
update #temp set col2='B' where GetID=@GetID
------
update #temp set GetID=null where GetID=@GetID
end
--輸出處理結果
select * from #temp
uj5u.com熱心網友回復:
你這種完全就是前臺程式員的思路,資料庫的強大在于能夠進行批處理。你現在的代碼還是前臺的那種遍歷,沒有效率可言。你直接這樣做不行嗎?
update #temp set col2='B'
where GetID is not null
update #temp set GetID=null
where GetID is null
uj5u.com熱心網友回復:
主要是根據傳入的臨時表處理復雜邏輯,update #temp set col2='B' where GetID=@GetID 只是個簡單例子。因為到時候做邏輯的時候,在select top 1 @GetID=GetID from #temp where GetID is not null 定義多一個變數,就可以隨時獲取到某列,然后再做邏輯。還是說有什么通用方法可以處理復雜邏輯的寫法
uj5u.com熱心網友回復:
取決于查找條件,查找條件盡量走索引uj5u.com熱心網友回復:
你貼出來的東西, 根本就沒什么可以優化的, 或者說能優化也優化不了多少。關鍵還是你所說的復雜邏輯,你沒有貼出來的那部分。
你要貼出完整的, 人家才能幫你優化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/16174.html
標籤:疑難問題
上一篇:SQL Server 用 graph table 如何寫 recursive query
下一篇:卡達八系統
