考虑以下(伪)代码。
int aMin = 10
int bMax = 0
Row selectedRow
foreach(row in rows):
if (row.a <= aMin && row.b >= bMax)
aMin = row.a
bMax = row.b
selectedRow = row
selectedRow
是否可以编写与此相关的SQL等效项,跟踪当前最低值a和最高值a,以找到与该标准匹配的单行?
答案 0 :(得分:0)
DECLARE @aMin int = 10
DECLARE @bMax int = 0
DECLARE @a int
DECLARE @b int
DECLARE table_cursor CURSOR FOR
(
SELECT a,b,--maybe more columns here
FROM your_table
)
OPEN table_cursor
FETCH NEXT FROM table_cursor INTO @a, @b
WHILE @@FETCH_STATUS = 0
BEGIN
if @a < @aMin and @b > @bMax
BEGIN
UPDATE your_table -- **PLEASE NOTE HERE THIS UPDATE IS RISKY TO EXECUTE, YOU MAY WANT TO RETURN MORE COLUMNS IN THE CURSOR TO MAKE THE ROWS FOR UPDATING UNIQUE**
SET a = @Min, b = @bMax
WHERE a = @a and b = @b
END
SELECT a,b, --maybe more columns here
FROM your_table
where a = @a and b = @b
FETCH NEXT FROM table_cursor INTO @a, @b
END
CLOSE table_cursor
DEALLOCATE table_cursor
我认为更好的表现是为每行添加标识列,以便在游标更新中,您可以按Where a = @a and b = @b and identity_row = @i <-- another variable you declared for storing row identifier
找到唯一的行