偶爾測試了一段小代碼,寫個循環
if object_id('tempdb..#TB') is not null drop table #TBgocreate table #TB( ID int)insert into #TB (ID)select 1union allselect 2union allselect 3union allselect 4union allselect 5--代碼1declare @i int set @i = 1while @i < 5begin update #TB set ID = ID,@i = @i + 1 select @iend
--代碼2set @i = 1while @i < 5begin update #TB set ID = ID set @i = @i + 1 select @iend
本來我覺得2段代碼是一致的。都是執行了5次,那么@i = 6
但實際上,代碼2是符合上述情況,執行了5次,@i = 6
但代碼1 卻只是執行了1次,@i = 6
對于這種情況,我只能猜測是update本身的機制。對于代碼1,每一條影響記錄,那么便執行一次@i = @i + 1。所以在一次循環里面就執行了5次,達到了while的閥值,跳出循環。
而對于代碼2,則沒有這個限制,順序執行。
當然這只是個人猜想,還請各位指導。
這么一個簡單的語句,一個不留神都踩坑,看來Sql Server里面的故事真不少啊
新聞熱點
疑難解答