我想为SQL服务器表创建一个递增的字母数字序列,它使用数字0-9,小写字母a-z和大写字母A-Z。所以系列会像0,1,2,3 ...... 9,a,b,c,d ...,x,y,z,A,B,C,D ...... X,Y,Z然后超过它将成为11,12,13 ...... 1a,1b,1c ...... 1X,1Y,1Z,然后21,22,23 ...... 2A,2B等等。
目标是增加一个字符串短的字符串ID,基本上使用基本的62字母数字系统递增。
我的第一个倾向是创建一个包含许多列的表,每列都会在系统中存储一个位置。所以像0,0,0,0,0,1这样的列;每次需要一个新值时,它会循环遍历列,根据需要递增,最终达到0,0,0,3,D,z等等。
有没有人对如何做到更聪明或更简洁?同样,目标是创建一个递增序列,即" short"就代表所需的地点或字符数而言。
答案 0 :(得分:1)
感谢@JohnCappelletti和Daniel Ballinger的回答:http://www.fishofprey.com/2011/08/convert-between-base-10-and-base-62-in.html
要记录:
在T-SQL中从Base 10转换为Base 62
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[Base62Encode](@a_number_to_convert [decimal](36, 0))
RETURNS [char](12) WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @v_modulo INTEGER;
DECLARE @v_temp_int decimal(38) = @a_number_to_convert;
DECLARE @v_temp_val VARCHAR(256) = '';
DECLARE @v_temp_char VARCHAR(1);
--DECLARE @c_base62_digits VARCHAR(62) = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
DECLARE @c_base62_digits VARCHAR(62) = '0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ';
IF ( @a_number_to_convert = 0 )
BEGIN
SET @v_temp_val = '0';
END
WHILE ( @v_temp_int <> 0 )
BEGIN
SET @v_modulo = @v_temp_int % 62;
SET @v_temp_char = substring( @c_base62_digits, @v_modulo + 1, 1 );
SET @v_temp_val = @v_temp_char + @v_temp_val;
SET @v_temp_int = floor(@v_temp_int / 62);
END
RETURN @v_temp_val;
END
在T-SQL中从Base 62转换为Base 10
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[Base62Decode](@a_value_to_convert [char](12))
RETURNS [decimal](36, 0) WITH EXECUTE AS CALLER
AS
BEGIN
DECLARE @v_iterator int;
DECLARE @v_length int;
DECLARE @v_temp_char VARCHAR(1);
DECLARE @v_temp_int bigint;
DECLARE @v_return_value decimal(38) = 0;
DECLARE @v_multiplier decimal(38) = 1;
DECLARE @v_temp_convert_val VARCHAR(256) = @a_value_to_convert;
--DECLARE @c_base62_digits VARCHAR(62) = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
DECLARE @c_base62_digits VARCHAR(62) = '0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ';
SET @v_length = len( @v_temp_convert_val );
SET @v_iterator = @v_length;
WHILE ( @v_iterator > 0 )
BEGIN
-- The character being converted
SET @v_temp_char = substring( @v_temp_convert_val, @v_iterator, 1 );
-- The index of the character being converted
SET @v_temp_int = charindex( @v_temp_char collate SQL_Latin1_General_CP1_CS_AS, @c_base62_digits collate SQL_Latin1_General_CP1_CS_AS ) - 1;
SET @v_return_value = @v_return_value + ( @v_temp_int * @v_multiplier );
SET @v_multiplier = @v_multiplier * 62;
SET @v_iterator = @v_iterator - 1;
END
RETURN @v_return_value;
END