在預存程序中示範使用case的例子(一)__儲存

來源:互聯網
上載者:User

  1. 示範case的預存程序

/*

當前的預存程序示範了如何在預存程序中使用case 語句. CASE 有兩種格式:   1. 簡單CASE 函數將某個運算式與一組簡單運算式進行比較以確定結果     CASE input_expression              WHEN when_expression THEN result_expression                  [ ...n ]          ELSE         else_result_expression     END          2. CASE 搜尋Function Compute一組布林運算式以確定結果。     CASE              WHEN Boolean_expression THEN result_expression                   [ ...n ]          ELSE          else_result_expression         END   兩種格式均支援可選的ELSE 參數。     說明: input_expression     使用簡單CASE 格式時所計算的運算式。input_expression 參數可以是Microsoft SQL Server 2005 Mobile Edition (SQL Server Mobile) 中的任何有效運算式。   WHEN when_expression     使用簡單CASE 格式時與input_expression 相比較的簡單運算式。when_expression 參數可以是任何有效SQL Server 運算式。input_expression 和每個when_expression 的資料類型必須相同,或者必須進行隱式轉換。   n     預留位置,表示可以使用多個WHEN when_expression THEN result_expression 子句或多個WHEN Boolean_expression THEN result_expression 子句。   THEN result_expression     當input_expression 等於when_expression 的計算結果為TRUE 或者Boolean_expression 的計算結果為TRUE 時,所返回的運算式。result expression 參數可以是任何有效SQL Server 運算式。   ELSE else_result_expression     比較運算結果都不為TRUE 時所返回的運算式。如果省略此參數並且比較運算的計算結果都不為TRUE,CASE 將返回NULL。else_result_expression 參數可以是任何有效SQL Server 運算式。else_result_expression 和任意result_expression 的資料類型必須相同,或者必須進行隱式轉換。   WHEN Boolean_expression     使用CASE 搜尋格式時所計算的布林運算式。Boolean_expression 可以是任何有效布林運算式。   */ ALTER PROCEDURE dbo.tt     @id int,      @strout nvarchar(100) output AS  declare @tmp int  /* 如果age的值為null,則表示沒有對應的記錄*/  select @tmp = case when age is null then -1 else age end from  Students where id = @id  SELECT @strout =  case     when @tmp = -1 then ' 沒有對應的記錄'     when (@tmp > 0 and   @tmp < 10) then ' 大於0,小於10歲'      when (@tmp > 10 and  @tmp < 20) then ' 大於10,小於20歲'      when (@tmp > 20 and  @tmp < 30) then ' 大於20,小於30歲'  else       ' 大於等於30歲'  end  RETURN     2. 測試表Students中的資料

ID NAME AGE SEX
1 小明 21 1
2 小芳 24 2
3   20 2
  3. 在查詢分析器中測試 1. declare @out nvarchar(100) exec tt @id = 1, @strout = @out output print ( @out)   輸出結果為 : 大於20 , 小於30歲 2.     declare @out nvarchar(100) exec tt @id = 4, @strout = @out output print ( @out)   輸出結果為 : 沒有對應的記錄

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.