zoukankan      html  css  js  c++  java
  • 在Sql的where中使用case进行不同字段筛选|Case的2种使用方法和一种少为人知的用途

    代码
    /* 
    简单方法,使用Or
    powry by 下载软件
    */

    declare @Status int
    set @Status = 1

    SELECT [ProductId] FROM Product 
    -- 产品状态筛选
    where 
    (
     (
    @status = 0)
     
    or(@status = 1 and IsActive=1 and SaleDateTime < GETDATE())--1:正在销售
     or(@status = 2 and IsActive=0)        --2:下架
     or(@status = 3 and stockCount <1)       --3:缺货
     or(@status = 3 and [Status] =4)        --3:自定义状态的缺货
     or(@status = 4 and SaleDateTime >getdate())     --:Comming
     or(@status = 4 and [Status] =1)        --:自定义状态的Comming
     --or(@key !='' and @key is not null and IsActive=1)   --搜索的时候将所有在线产品全部搜出来
    )  


    /*
    第二种方法,使用case,都说where不能使用case,上学之痛刚才说是可以的,主要是很多人不知道可以在case的end后面进行比较,我也是刚刚仔细看了联机手册发现的,再此着重讲一下原理
    powery by 上学之痛
    */

    declare @status int
    set @status = 1

    SELECT [ProductId] FROM Product 
    -- 产品状态筛选
    where case 
     
    when(@status = 0then 1
     
    when(@status = 1 and IsActive=1 and SaleDateTime < GETDATE())then 1--1:正在销售
     when(@status = 2 and IsActive=0then 1      --2:下架
     when(@status = 3 and stockCount <1)  then 1     --3:缺货
     when(@status = 3 and [Status] =4)  then 1      --3:自定义状态的缺货
     when(@status = 4 and SaleDateTime >getdate()) then 1    --:Comming
     when(@status = 4 and [Status] =1then 1       --:自定义状态的Comming
     --when(@key !='' and @key is not null and IsActive=1) then 1  --搜索的时候将所有在线产品全部搜出来
     end = 1

    CASE 具有两种格式:

    简单 CASE 函数将某个表达式与一组简单表达式进行比较以确定结果。
    Simple CASE function: 

    declare @Status int
    set @Status = 3
    select case @Status
    when 2+1 then 5
    end

    上面代码示:case将某个表达式:@Status 和when后面的接的表达式2+1(他必将可以和 case inpu ,当然是数字和数字,字符和字符进行比较)进行比较,如果比较的结果为true,则返回then里面的值

    CASE 搜索函数计算一组布尔表达式以确定结果。

    Searched CASE function:

    declare @Status int
    declare @bb bit
    set @Status = 3
    select case
    when 1=1 then 5

    when 2=2 then 5
    end

    代码所示:case直接根据一组when的表达式进行确定值,当然,即使找到多个你自己认为符合的表达式,但是他会以第一条优先

    重点:不管是简单模式还是搜素函数,他都会返回一个结果,就是then的结果,因此你可以得道一条数据,很多人知道case可以返回值,却不知道可以直接在end后面接操作符继续进行计算和操作

    declare @Status int
    declare @bb bit
    set @Status = 3
    select case
    when 1=1 then 5
    when 2=2 then 6
    end - 6

    结果为-1,

    同理,当case的搜索函数用在where后面的时候,你只要让的then的返回值和你设定的某个值进行对比,就可以进行筛选了

    再此,感谢下载软件和上学之痛提出宝贵的意见和详细的讲解

  • 相关阅读:
    python基础练习:
    py+selenium切换到新弹出窗口通用方法
    Python 异常处理
    验证码自动化认证部分,可能由于分辨率导致截图不正确
    基于Tesseract的OCR图像识别
    Spark相关知识
    Hive和数据库除了拥有类似的查询语言,再无类似之处;关系型数据库和非关系型数据库的优缺点
    sed替换^A(01),02,03等特殊字符
    Python操作adb命令脚本
    python从放弃到放弃
  • 原文地址:https://www.cnblogs.com/tthxnz/p/1751799.html
Copyright © 2011-2022 走看看