![](/img/trans.png)
[英]Update a column in table A based on values in table B using a CASE statement
[英]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=@b
與where @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.