代码之家  ›  专栏  ›  技术社区  ›  Ramji

满足case条件时执行insert语句

  •  0
  • Ramji  · 技术社区  · 8 年前

    我有一个具有insert语句的存储过程。当用户提供所有值为0时,该过程将执行insert语句。如果用户提供不同的值,则应返回错误语句。

    case when @test1=0,@test2=0,@test3=0 then 
    {Insert statement} 
    Else
    Case when @test1=0,@test2=0,@test3=1
    {select “All cases should be 0”}
    Else
    Select “Please provide data”
    

    在本例中,我认为case条件可以正常工作,但是在阅读了文档和其他一些链接之后,编写这样的语句在语法上似乎是错误的。

    任何其他可能的方法来解决这个问题。

    2 回复  |  直到 8 年前
        1
  •  1
  •   Gordon Linoff    8 年前

    if case

    if @test1=0 and @test2=0 and @test3=0 
    begin 
        {Insert statement} 
    end;
    Else if @test1=0 and @test2=0 and @test3=1
    begin
        {select “All cases should be 0”}
    end
    Else
    begin
        Select “Please provide date”
    end;
    
        2
  •  0
  •   Shushil Bohara    8 年前

    IF 0 COALESCE NULLIF

    IF (@test1 = 0 AND @test2 = 0 AND @test3 = 0) 
    BEGIN 
        INSERT INTO tmpTable(val1)
        SELECT val1 FROM <table_name>
    END
    ELSE IF COALESCE(NULLIF(@test1, 0), NULLIF(@test2, 0), NULLIF(@test3, 0)) IS NOT NULL
    BEGIN
        SELECT 'All cases should be 0'
    END
    ELSE
    BEGIN
        SELECT 'Please provide data'
    END