我只需要返回查询返回的最后一行,所以我需要将其按DESC顺序放置并限制为1,但是sql不喜欢ORDER BY语句。我该如何编码?
DECLARE @firstNum INT, @secondNum INT, @thirdNum INT, @evenSum INT
SET @firstNum = 1
SET @secondNum = 2
set @thirdNum = 2
SET @evenSum = 2
WHILE (@thirdNum <= 4000000)
BEGIN
SET @thirdNum = @firstNum + @secondNum
SET @firstNum = @secondNum
SET @secondNum = @thirdNum
IF (@thirdNum % 2) = 0
SET @evenSum += @thirdNum
PRINT 'Answer = ' + CONVERT(VARCHAR, @evenSum)
ORDER BY @evenSum DESC
END```
您可以在循环之后直接打印:
DECLARE @firstNum INT, @secondNum INT, @thirdNum INT, @evenSum INT
SET @firstNum = 1
SET @secondNum = 2
set @thirdNum = 2
SET @evenSum = 2
WHILE (@thirdNum <= 4000000)
BEGIN
SET @thirdNum = @firstNum + @secondNum
SET @firstNum = @secondNum
SET @secondNum = @thirdNum
IF (@thirdNum % 2) = 0
SET @evenSum += @thirdNum
END
PRINT 'Answer = ' + CONVERT(VARCHAR, @evenSum)
除非我完全错过了您要实现的目标,否则您不是只想这样做吗?
DECLARE @firstNum INT, @secondNum INT, @thirdNum INT, @evenSum INT
SET @firstNum = 1
SET @secondNum = 2
set @thirdNum = 2
SET @evenSum = 2
WHILE (@thirdNum <= 4000000)
BEGIN
SET @thirdNum = @firstNum + @secondNum
SET @firstNum = @secondNum
SET @secondNum = @thirdNum
IF (@thirdNum % 2) = 0
SET @evenSum += @thirdNum
END
PRINT 'Answer = ' + CONVERT(VARCHAR, @evenSum)
您尝试使用'ORDER BY'进行的操作没有用,因为您没有在处理数据集,没有什么可“排序”的-您有一些变量,并且正在进行一些计算在它们上循环直到满足特定条件-您想知道循环结束时最后一次迭代时@evensum的值是什么。因此,您需要做的就是等待代码脱离循环并输出值。