問(wèn)題描述
首先讓我說(shuō)我知道我知道這種循環(huán)很可怕,你不應(yīng)該在 Transact SQL 中使用它們.但是,出于某些目的(這些目的無(wú)關(guān)緊要,所以不要問(wèn)我你想做什么!?")你只需要這樣做.我不想,但我必須.
Let me start out by saying I know I KNOW that these kind of loops are horrible and you shouldn't use them in Transact SQL. But, for some purposes (those purposes being irrelevant so don't ask me "what're you trying to do!?") ya just have to. I don't want to, but I gotta.
無(wú)論如何.有沒(méi)有辦法讓 T-SQL 中的 while 循環(huán)在復(fù)雜的條件語(yǔ)句上終止?就像,在 C# 中,我只想說(shuō) while (i > -10 && i <10) ,因?yàn)槲蚁Mh(huán)在標(biāo)記值介于 -10 和 10 之間時(shí)終止,但我只是...可以不知道怎么做.
Anyway. Is there some way to have a while loop in T-SQL terminate on a complex conditional statement? like, in C# I'd just say while (i > -10 && i < 10) , because I want the loop to terminate when the sentinel value is between -10 and 10, but I just... can't figure out how to do it.
這可能非常簡(jiǎn)單……或者……不可能.請(qǐng)指教.
It's probably excruciatingly simple... or.. impossible. Please advise.
現(xiàn)在,我剛剛得到
WHILE @N <> 0
BEGIN
--code and such here
END
推薦答案
你必須看WHILE語(yǔ)句的聲明:
You must look at declaration of WHILE statement:
WHILE Boolean_expression
{ sql_statement | statement_block | BREAK | CONTINUE }
首先,你可以像 Dan 所說(shuō)的那樣使用復(fù)雜的 Boolean_expression:
First of all you can use complex Boolean_expression as Dan said:
WHILE @N > -1 AND @N <10
BEGIN
END
如果您想為代碼添加更多靈活性,可以使用 IF 與 BREAK,類似這樣:
If you want to add more flexibility to you code you can use IF with BREAK, something like this:
WHILE @N > -1 AND @N <10
BEGIN
-- code
IF (SELECT MAX(ListPrice) FROM Production.Product) > $500
BREAK
END
-- code
END
退出循環(huán)或使用 CONTINUE 跳過(guò)一個(gè)循環(huán).
to go out of cycle or use CONTINUE to skip one cycle.
這篇關(guān)于在 T-SQL 中具有多個(gè)條件的 while 循環(huán)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!