------解决方案-------------------- -- ============================================= -- Create scalar function (FN) -- ============================================= IF EXISTS (SELECT * FROM sysobjects WHERE name = N'GetExcelColumnTitle') DROP FUNCTION GetExcelColumnTitle GO
CREATE FUNCTION GetExcelColumnTitle (@N bigint ) RETURNS varchar(10) AS BEGIN if @N<=0 return 'Error:01'
while @Num>25 and @i<8 begin if @i=1 set @C1= char(65+@Num%26) else if @i=2 set @C2= char(65+@Num%26) else if @i=3 set @C3= char(65+@Num%26) else if @i=4 set @C4= char(65+@Num%26) else if @i=5 set @C5= char(65+@Num%26) else if @i=6 set @C6= char(65+@Num%26) else if @i=7 set @C7= char(65+@Num%26) set @Num=(@Num/26)-1 set @i = @i+1 end
if @i>8 return 'Error:02' else if @i=1 set @C1= char(65+@Num%26) else if @i=2 set @C2= char(65+@Num%26) else if @i=3 set @C3=char(65+@Num%26) else if @i=4 set @C4= char(65+@Num%26) else if @i=5 set @C5= char(65+@Num%26) else if @i=6 set @C1= char(65+@Num%26) else if @i=7 set @C7= char(65+@Num%26) else if @i=8 set @C8= char(65+@Num%26)
return case when @i=1 then @C1 when @i=2 then @C2+@C1 when @i=3 then @C3+@C2+@C1 when @i=4 then @C4+@C3+@C2+@C1 when @i=5 then @C5+@C4+@C3+@C2+@C1 when @i=6 then @C6+@C5+@C4+@C3+@C2+@C1 when @i=7 then @C7+@C6+@C5+@C4+@C3+@C2+@C1 when @i=8 then @C8+@C7+@C6+@C5+@C4+@C3+@C2+@C1 else 'Error:03' end END GO -- ============================================= -- Example to execute function -- ============================================= SELECT dbo.GetExcelColumnTitle(703) --結果: --AAA GO