带参数的CASE语句构造

时间:2017-11-23 15:49:24

标签: sql sql-server tsql case

请有人告诉我,以下结构有什么问题?:

 CASE @CountryID
        WHEN 1 THEN SET @String = REPLACE(@String,'+420','')
        WHEN 2 THEN SET @String = REPLACE(@String,'+421','')    
        WHEN 3 THEN SET @String = REPLACE(@String,'+359','')    
        WHEN 4 THEN SET @String = REPLACE(@String,'+7','')  
        WHEN 5 THEN SET @String = REPLACE(@String,'+48','') 
        WHEN 7 THEN SET @String = REPLACE(@String,'+63','') 
    END

@CountryIDINT

问题出现在CASE声明构造中,因为IF语句运行良好,但我看不到任何故障,尝试了不同类型的案例构建并搜索文档。

任何提示都会受到赞赏。

2 个答案:

答案 0 :(得分:5)

您需要使用:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Upload image -->
<section id="sectionDragAndDrop">
    <div class="drop" id="drop">
        <p>Drag & drop or click here to upload an image.</p>
    </div>
    <input class="file-upload hidden" id="fileUpload" type="file">
</section>

<!-- Resize image -->
<section class="hidden" id="sectionResize">
    <div class="image-resize" id="imageResize"></div>
</section>
  <button id="crop" class="btn" id="crop"><span class='fa fa-crop'></span> Submit</button>
<!-- Insert thumbnail -->
<section class="hidden" id="sectionThumbnail">
    <div class="thumbnail" id="thumbnail"></div>
</section>

CASE is expression ,但您将其用作SELECT @String = CASE @CountryID WHEN 1 THEN REPLACE(@String,'+420','') WHEN 2 THEN REPLACE(@String,'+421','') WHEN 3 THEN REPLACE(@String,'+359','') WHEN 4 THEN REPLACE(@String,'+7','') WHEN 5 THEN REPLACE(@String,'+48','') WHEN 7 THEN REPLACE(@String,'+63','') -- ELSE @String -- to avoid NULL if no country found END; (例如在Oracle / DB2中可用)

Oracle支持 CASE statement (在CASE statement中不可用):

T-SQL

CASE expression

CASE
    WHEN jobid = 'PU_CLERK' THEN sal_raise := .09;
    WHEN jobid = 'SH_CLERK' THEN sal_raise := .08;
    WHEN jobid = 'ST_CLERK' THEN sal_raise := .07;
    ELSE sal_raise := 0;
  END CASE;

修改

HABO所述,您可以将其重写为:

 appraisal :=
      CASE grade
         WHEN 'A' THEN 'Excellent'
         WHEN 'B' THEN 'Very Good'
         WHEN 'C' THEN 'Good'
         WHEN 'D' THEN 'Fair'
         WHEN 'F' THEN 'Poor'
         ELSE 'No such grade'
      END;

或者在SQL Server 2012及更高版本中,您可以使用SELECT @String = REPLACE(@String, CASE @CountryID WHEN 1 THEN '+420' WHEN 2 THEN '+421' WHEN 3 THEN '+359' WHEN 4 THEN '+7' WHEN 5 THEN '+48' WHEN 7 THEN '+63' ELSE '' END, '');

CHOOSE

答案 1 :(得分:2)

@ lad2025重写了有效的代码(并且有一个很好的解释!)。我想指出在SQL Server中,我更喜欢:

SELECT @String = REPLACE(@String, v.str, '')
FROM (VALUES (1, '+420'), (2, '+421'), (3, '+359'), (4, '+7'),
             (5, '+48'), (7, '+63')
     ) v(countryId, str)
WHERE v.countryId = @CountryID;

如果没有匹配,我认为这不会改变@String的值。