"where"子句中的SQL Switch/Case [英] SQL Switch/Case in 'where' clause

查看:360
本文介绍了"where"子句中的SQL Switch/Case的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试四处搜寻,但是找不到任何可以帮助我的东西.

I tried searching around, but I couldn't find anything that would help me out.

我正在尝试在SQL中执行此操作:

I'm trying to do this in SQL:

declare @locationType varchar(50);
declare @locationID int;

SELECT column1, column2
FROM viewWhatever
WHERE
CASE @locationType
    WHEN 'location' THEN account_location = @locationID
    WHEN 'area' THEN xxx_location_area = @locationID
    WHEN 'division' THEN xxx_location_division = @locationID

我知道我不必在每一个末尾都添加'= @locationID',但是我什至无法获得接近正确的语法. SQL一直在第一行WHEN上抱怨我的'='...

I know that I shouldn't have to put '= @locationID' at the end of each one, but I can't get the syntax even close to being correct. SQL keeps complaining about my '=' on the first WHEN line...

我该怎么做?

推荐答案

declare @locationType varchar(50);
declare @locationID int;

SELECT column1, column2
FROM viewWhatever
WHERE
@locationID = 
  CASE @locationType
      WHEN 'location' THEN account_location
      WHEN 'area' THEN xxx_location_area 
      WHEN 'division' THEN xxx_location_division 
  END

这篇关于"where"子句中的SQL Switch/Case的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆