簡體   English   中英

使用 CASE 語句根據變量選擇列

[英]Selecting column based on variable using CASE statement

我無法弄清楚如何查找有關此聲明的更多信息。

這是一個存儲過程,在@loc_nbr 和@loc_type 中傳遞了兩個字符串。 似乎搜索@loc_nbr 的列是根據傳入的@loc_type 字符串選擇的。任何人都可以向我解釋這一點,或者更好的是,只需將我指向參考頁面,因為我無法找到更多信息。

where @loc_nbr = 
case when @loc_type = 'Chain' then @loc_nbr
    when @loc_type = 'Operation' then operation_nbr
    when @loc_type = 'Region' then region_nbr
    when @loc_type = 'Area' then area_nbr
    when @loc_type = 'District' then district_nbr
    when @loc_type = 'Store' then C2.str_nbr end

我對 case 語句在這種情況下與 WHERE 子句相關的工作方式感到困惑。 如何搜索該列? THEN 在這種情況下是一列 (operation_nbr, region_nbr) 而@loc_nbr 是一個varchar

這很簡單,我會盡力解釋。

首先是case表達式。

case when <some expression=true> then return this else that end

當單個case表達式中有多個case - when語句時,它將依次計算每個語句並返回第一個計算結果為true的表達式。

where子句為每一行計算一個表達式,如果表達式為true ,則返回該行,否則將其排除。

您可以使用where 1=1 - 對每一行評估為true ,因此返回所有行。

如果您有兩個變量@a@b ,並將它們都設置為1 ,則where @a=@bwhere @b=@a相同,並返回所有行。

以同樣的方式, where 1 = case when 1=1 then 1 else 0 end將返回所有行 - 評估case表達式,1 是否等於 1? 是的,所以表達式返回1並且它等於=另一側的1 ,因此where子句對於所有行都是true

現在考慮以下內容,

where @loc_nbr = case when @loc_type='chain' then @loc_nbr else 1 end

如果@loc_type確實包含 'chain' 則case表達式為true並且它返回@loc_nbr ,在這種情況下,我們有where @loc_nbr=@loc_nbr對於所有行都為true並且不進行過濾。 如果@loc_type是其他任何東西,我們有where @loc_nbr=1所以只有當@loc_nbr的值為1時才會返回任何單獨的行。

因此,現在您可以開始將列中的值引入到case表達式中。

where @loc_nbr =
  case when @loc_type = 'Chain' then @loc_nbr <------------No filtering done, all rows returned, essentially where 1=1
       when @loc_type = 'Operation' then operation_nbr <---A row is returned only if the value of column operation_nbr = @loc_nbr
  end

所以你可以看到你可以繼續添加額外的when子句,並且只有為@loc_type的值指定的列用於與@loc_nbr進行比較。 如果該列的值等於@Loc_nbr ,則返回每一行

@Loc_nbr可以是字符串,表中的列operation_nbr, region_nbr等可以是integer ,如果@loc_nbr是字符串,它將被隱式轉換為int以進行比較。 為了清楚起見,最好明確地轉換它們。

如果它看起來像這樣,也許對您來說更有意義:

where 
  (@loc_type = 'Chain') OR
  (@loc_type = 'Operation' AND operation_nbr = @loc_nbr) OR
  (@loc_type = 'Region' AND region_nbr = @loc_nbr) OR
  (@loc_type = 'Area' AND area_nbr = @loc_nbr) OR
  (@loc_type = 'District' AND district_nbr = @loc_nbr) OR
  (@loc_type = 'Store' AND C2.str_nbr = @loc_nbr)

它們本質上是相同的邏輯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM