SQL中的While循环替换

时间:2018-07-04 07:19:38

标签: sql-server tsql sql-server-2014

请阅读以下代码,我使用while循环通过将ADTV标准降低10%来获得前30名,直到我达到前30名时,它都会继续降低。我想替换while循环

DECLARE
@parent_symbol NVARCHAR(20) = 'SXXE',
@index_symbol NVARCHAR(20) = 'ISX30P',
@top50_symbol NVARCHAR(20) = 'SX5E',
@true CHAR(4) = 'TRUE',
@false CHAR(5) = 'FALSE',
@top INT = 30,
@adtv_filter INT = 30000000,
@sector_max INT=6,
@count INT,
@adtv INT,
@remainingCount INT;

--select * from universe_temp where selection_flag = 'TRUE'
--Delete from universe_temp
    SET @count= (SELECT COUNT(dj_id) 
FROM universe_temp 
WHERE selection_flag= @true);
print(@count)
--while (@count<@top)
set @adtv = @adtv_filter-((10*@adtv_filter)/100)
print(@adtv)

set @remainingCount = @top-@count
print(@remainingCount)
while (@count<@top)
Begin
;with remaining_top as (
select top(@remainingCount) dj_id from universe_temp
                         WHERE selection_flag=@false and adtv3m >= @adtv and reason_for_rejection = 'Not in Top 30'
                         ORDER BY market_capitalization_rank
)


--select * from remaining_top

UPDATE u
            SET u.selection_flag=  @true
                --,u.reason_for_rejection= CASE  WHEN t.dj_id IS NULL AND u.reason_for_rejection IS NULL THEN 'Not in Top '+CAST(@top AS NVARCHAR) ELSE reason_for_rejection END
FROM universe_temp u 
         JOIN remaining_top t ON u.dj_id=t.dj_id

set @count= @count + (select count(*) from  universe_temp where selection_flag= @true)
        End

1 个答案:

答案 0 :(得分:0)

该脚本有很多问题,我真的不知道从哪里开始。要记住的一件事是您正在减少循环之外的条件,另一件事是您增加了计数,而不是在每个循环结束时刷新它,等等。

如果您只是想按某些标准挑选出前30名“无论如何”,那么这可能有助于避免使用循环?

--Deselect all rows
UPDATE universe_temp SET selection_flag = @false;

--Now select the top x
WITH Ranked AS (
    SELECT
        *,
        DENSE_RANK() OVER (ORDER BY adtv3m DESC, market_capitalization_rank DESC) AS rank_id 
    FROM
        universe_temp)
UPDATE
    r
SET
    selection_flag = @true
FROM
    Ranked r
WHERE
    r.rank_id <= @top;

--Find the threshold (bonus)
SELECT MIN(adtv3m) FROM universe_temp WHERE selection_flag = @true;

但是我真的不知道您要在这里实现什么,如何将数据放入“ universe_temp”表,这代表什么等等。