12

我有字母“a”、“b”、“c”。我希望我的结果在 TSQL 中分别为“b”、“c”、“d”。我会用什么来实现这一目标?

4

5 回答 5

19

用于ASCII获取字符的值,加一,CHAR用于将值转换回字符。

SELECT CHAR(ASCII('a') + 1)
于 2012-08-29T13:26:18.403 回答
11

这就是你为一封信做的事情

DECLARE @myletter char(1) = 'a';
SELECT CHAR(ASCII(@myletter)+1);
于 2012-08-29T13:25:21.957 回答
2

带有两个 SQL 程序的 3 个字母的字母计数器

(a,b...z,aa,ab...zy,zz,aaa...zzz):

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

alter procedure letraMas
@letraEntra as char( 1),
@letraSale as char( 1) OUTPUT,
@seLleva as bit  OUTPUT

as

--set @letraEntra = 'w'
--set @letraSale = 'm'
set @seLleva = 0

select
@letraSale = CASE
        WHEN @letraEntra = '' or (@letraEntra is null) or @letraEntra = 'z'
        THEN 'a'
    WHEN @letraEntra < 'z'
        THEN CHAR (ASCII( @letraEntra) + 1)
end

if @letraEntra = 'z' set @seLleva = 1

return

SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

/* USO:
declare
@tareaEntra as char(3),
@tareaSale as char(3)
set @tareaEntra = 'xzz'
       EXEC tareaMas @tareaEntra, @tareaSale OUTPUT
*/
alter procedure tareaMas
@tareaEntra as char( 3),
@tareaSale as char( 3) OUTPUT

as
declare @charU as char(1 )     -- char de U_nidades albabéticas
declare @charD as char(1 )     -- char de D_ecenas albabéticas
declare @charC as char(1 )     -- char de C_entenas albabéticas
declare @letraSale as char(1 )        -- char de C_entenas albabéticas
declare @seLleva as bit

set @tareaEntra   = right('   ' + rtrim (@tareaEntra), 3)

set @charU = substring(@tareaEntra , 3, 1)
set @charD = substring(@tareaEntra , 2, 1)
set @charC = substring(@tareaEntra , 1, 1)

EXEC letraMas @charU, @letraSale OUTPUT, @seLleva OUTPUT
set @charU = @letraSale
if @seLleva = 1
BEGIN
        EXEC letraMas @charD, @letraSale OUTPUT, @seLleva OUTPUT
        set @charD = @letraSale
        if @seLleva = 1
        BEGIN
               EXEC letraMas @charC, @letraSale OUTPUT, @seLleva OUTPUT
               set @charC = @letraSale
        END
END

set @tareaSale = ltrim(@charC + @charD + @charU)
return
于 2016-02-23T10:18:33.330 回答
1

这是 Jonathan Wood 实现的 CTE

;WITH cte AS
   (SELECT  CHAR(ASCII('a')) [char], 1 [count]
    UNION ALL
    SELECT  CHAR(ASCII('a') + cte.count) [char], cte.count + 1 [count]
    FROM    cte)
SELECT  TOP(26) cte.count[pos], cte.char
FROM    cte

您可以像那样使用它,也可以将结果插入到表变量或临时表中并在上面使用它。

我还要给出的另一个提示是,在您的数据库中有一个包含此 cte 数据的表,那么将来加入它并出于任何目的或原因使用它会更容易。

于 2014-08-20T07:21:06.403 回答
0
DECLARE @Letters AS TABLE
(
    Letter CHAR(1)
)
INSERT INTO @Letters
        ( Letter )
VALUES  ( 'A' )
INSERT INTO @Letters
        ( Letter )
VALUES  ( 'B' )
INSERT INTO @Letters
        ( Letter )
VALUES  ( 'C' )
SELECT CHAR(ASCII(Letter) + 1) FROM @Letters

在 SQL 中使用表变量的示例,但上述任何方法都可以为您完成。显然取决于您使用什么方法来整理信件列表。

于 2012-08-29T13:36:50.637 回答