【问题标题】:Whats wrong? SQL case怎么了? SQL 案例
【发布时间】:2016-01-17 18:03:02
【问题描述】:

我有这个程序,但我看不到我的错误,有人吗?我想添加一些文本并只打印人声。

create procedure sacaVocales
@vocales varchar(20)
as
begin
declare @repeticiones int = len(@vocales)
declare @contador int = 1
declare @resultado varchar(20)
declare @dato varchar(1)
while @contador<=@repeticiones
begin
select @dato = SUBSTRING(@vocales, @contador, @contador+ 1)
    case @dato
    when 'a' then @resultado = @resultado + @dato
    when 'e' then @resultado = @resultado + @dato
    when 'i' then @resultado = @resultado + @dato
    when 'o' then @resultado = @resultado + @dato
    when 'u' then @resultado = @resultado + @dato
set @contador = @contador + 1
end
print @resultado
end

我的错误离“案例”很近

【问题讨论】:

  • case 开始之前缺少end..也是,
  • ,已添加!什么结局?现在我的错误接近'='
  • @dato 是列别名。你不能在同一个查询中使用它,你正在使用 case
  • @dato 是来自子字符串的 varchar,是从我的文本中获取所有长度的方法
  • 您在最终的WHEN 之后、SET @contador 之前缺少一个END

标签: sql-server tsql case procedure


【解决方案1】:

另一种收集元音的方法:

declare @Vocales as VarChar(20) = 'vocales';
declare @Repeticiones as Int = Len( @Vocales );
declare @Contador as Int = 1;
declare @Resultado as VarChar(20) = '';
declare @Dato as VarChar(1);

while @Contador <= @Repeticiones
  begin
  set @Dato = Substring( @Vocales, @Contador, @Contador + 1 );
  if @Dato in ( 'a', 'e', 'i', 'o', 'u' )
    set @Resultado += @Dato;
  set @Contador += 1;
  end;

print @Resultado;

【讨论】:

    【解决方案2】:

    几件事。

    正如 VKP 在 cmets 中提到的,您不能在同一个查询中从 CASE 语句中提取数据,要解决这个问题,您可以为 CASE 语句创建一个额外的 SELECT

    其次,使用 CASE 时,THEN 之后不需要等号 (=)。 “THEN”本质上是等号,所以只需输入您希望它相等的值。

    如果您尝试此操作,查询将成功运行:

    DECLARE @vocales VARCHAR(20) = 'vocales'
    declare @repeticiones int = len(@vocales)
    declare @contador int = 1
    declare @resultado varchar(20)
    declare @dato varchar(1)
    while @contador<=@repeticiones
    begin
    select @dato = SUBSTRING(@vocales, @contador, @contador+1)
    SELECT
        case @dato
            when 'a' then @resultado + @dato
            when 'e' then @resultado + @dato
            when 'i' then @resultado + @dato
            when 'o' then @resultado + @dato
            when 'u' then @resultado + @dato
        END
    set @contador = @contador + 1
    end
    print @resultado
    

    然而,目前这个查询只会提供与@vocales 值长度相等的NULL 值。这是因为参数 @resultado 的值从未被声明,并且在您的 CASE 语句中,您将 NULL 值添加到始终等于 NULL 的已知值。

    让我知道您正在寻找什么输出,我可以修改我的查询以帮助您到达那里。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-29
      • 1970-01-01
      相关资源
      最近更新 更多