分配给变量的错误值

Wrong value assigned to variable

我已经开始在 SSMS 2012 中起草一个标量函数来获取一个字符串并交换任何出现的 3 个十六进制 URL 字符(%2b%2f%3d) 及其各自的单个字符(-/=):

DECLARE @OutputText as VARCHAR(100)
DECLARE @c as Int   
DECLARE @cIn as CHAR(3)
DECLARE @cOut as CHAR(1)
DECLARE @s as Int

SET     @OutputText = '%2bBWCq6sE7OU%3d'
SET     @c = 1

WHILE @c <= 3
    BEGIN
        -- Set the search/replace characters depending on iteration
        IF  @c = 1
            SET @cIn = '%2b'
            SET @cOut = '-';
        IF  @c = 2
            SET @cIn = '%2f'
            SET @cOut = '/';
        IF  @c = 3
            SET @cIn = '%3d'
            SET @cOut = '=';

        SET @s = PATINDEX('%' + @cIn +'%', @OutputText)

        WHILE @s > 0
            BEGIN

                PRINT 'Character Loop: ' + CAST(@c as VARCHAR(1)) + ' | looking for ' + @cIn + ' within ' + @OutputText
                PRINT '(Replace ' + @cIn + ' with ' + @cOut + ')'
                PRINT '-- ' + @cIn + ' found at position: ' + CAST(@s as VARCHAR(2))

                SET @OutputText = STUFF(@OutputText, PATINDEX('%' + @cIn +'%', @OutputText) - 1, 3, @cOut)

                PRINT '>> OutputText now: ' + @OutputText + CHAR(10)

                SET @s = PATINDEX('%' + @cIn +'%', @OutputText)

            END

    SET     @c = @c + 1

    END

PRINT 'Final output: ' + @OutputText

各种PRINTreturn这个:

注意第一个字符循环输出显示 Replace %2b with = ... 但是 if 语句应该将 @cOut 设置为 - 而不是 =@c = 1.

另一个小问题是,在输出显示 %2b found at position: 的位置,给定的位置编号似乎比应有的高 1,就像它忽略了 @cIn%

在您的 If 语句中,@cout 的每个设置都会发生,因为它们不是 IF 的一部分。只有 IF 执行后的下一行。您需要将它们包装在 Begin End:

IF  @c = 1
begin
    SET @cIn = '%2b'
    SET @cOut = '-'
end
else IF  @c = 2
begin
    SET @cIn = '%2f'
    SET @cOut = '/'
end
else IF  @c = 3
begin
    SET @cIn = '%3d'
    SET @cOut = '='
end

证明这一点:

declare @thing int = 2

if @thing=1
select 'ralph'
select 'charles'

if @thing = 2
select 'ralph2'
select 'charles2'

这将产生 charles、ralph2、charles2

而这个(开始结束):

declare @thing int = 2

if @thing=1
begin
    select 'ralph'
    select 'charles'
end

if @thing = 2
begin
    select 'ralph2'
    select 'charles2'
end

将正确生成 ralph2、charles2