Odd error using IF/ELSE IF statements

雨燕双飞 提交于 2019-12-01 20:11:37

Since only the top number of records are difference. You can try this

declare @num int 

SET @num = CASE @indexName 
                    WHEN 'A' THEN 400
                    WHEN 'B' THEN 75
                    WHEN 'C' THEN 300
                    ELSE  100
            END

select top (@num) * into #temp from #pretemp order by EMRev desc

The SQL parser looks for all places that might create a temp table, and only allows a given temp table name to be used ONE time. The solution is to do something like this:

select * into #temp from #pretemp where 1=2

IF @indexName = 'A'
    begin insert into #temp select top 400 * from #pretemp order by EMRev desc end
ELSE IF @indexName = 'B'
    begin insert into #temp select top 75 * from #pretemp order by EMRev desc end
ELSE IF @indexName = 'C'
    begin insert into #temp select top 300 * from #pretemp order by EMRev desc end
ELSE 
    begin insert into #temp select top 100 * from #pretemp order by EMRev desc end

The where 1=2 creates the table structure with zero records... Then the if statements populate the temp table.

Cheers!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!