SQLServer中Case when的一个意外问题
在论坛回答问题时,发现测试脚本会出现如下问题,百思不得其解。
set nocount on
create table test(a varchar(10))
insert into test select 'a'
insert into test select 'b'

declare @str1 varchar(8000)
declare @str2 varchar(8000)
set @str1=''
set @str2=''

select @str1=@str1+a from test order by a
print @str1 --返回ab

select @str2=@str2+a from test
order by
case a when 'a' then 1
when 'b' then 2 else 99 end

print @str2 --返回b

drop table test
set nocount off
上面的@str2会丢失前面的所有记录,只保留order by的最后一条-_-||






















上面的@str2会丢失前面的所有记录,只保留order by的最后一条-_-||