Geo*_*tis 0 t-sql sql-server while-loop
我正在使用sql服务器。
我有一段这样的代码
while(@@rowcount>0)
begin
--do stuff
end
Run Code Online (Sandbox Code Playgroud)
问题是,我想做一些整洁的事情,以确保第一次迭代能够运行。你建议在前面放什么?目前,我已经使用了
select 'Calling this to initialize @@rowcount to 1'
Run Code Online (Sandbox Code Playgroud)
这是不言自明的,但如果有更好的东西,我想知道。
添加变量允许您单独处理初始条件并保留@@RowCountif做的事情可能有几个步骤的值:
declare @RowCount as Int = 42;
-- Initialize @RowCount to skip the loop entirely, if appropriate.
while @RowCount > 0
begin
-- Do stuff;
set @RowCount = @@RowCount;
-- Perhaps do more stuff that might affect @@RowCount .
end;
Run Code Online (Sandbox Code Playgroud)
或者,可以使用变量来仅处理循环的第一次传递:
declare @FirstPass as Bit = 1;
-- Initialize @FirstPass to skip the loop entirely, if appropriate.
-- Note that the loop will always be entered once if @@RowCount has not been cleared.
while @@RowCount > 0 or @FirstPass = 1
begin
set @FirstPass = 0;
-- Do stuff;
end;
Run Code Online (Sandbox Code Playgroud)
我更喜欢使用第一种方法,因为它清晰、简单,并且提供了@@RowCount可用于日志记录、调试等的捕获值,而无需担心哪些语句可能会更改该值。
| 归档时间: |
|
| 查看次数: |
7423 次 |
| 最近记录: |