【问题标题】:if statement using a query in sql在 sql 中使用查询的 if 语句
【发布时间】:2013-01-08 21:58:29
【问题描述】:

我想问一下如何在SQL中使用IF statement进行条件检查,类似于下面的例子..

if (select* from table where id = @id) = 1 --if this returns a value

insert statement


else

update statement

go

或类似使用存储过程的东西...

if (exec SP_something 2012, 1) = 0 

insert statement

else

update stement

或者可能通过在 sql 语句中使用 UDF,例如...

if (select dbo.udfSomething(1,1,2012)) = 0 

insert statement

else

update statement

go

【问题讨论】:

    标签: sql sql-server stored-procedures if-statement sql-server-2000


    【解决方案1】:

    你会想做这样的事情:

    IF (SELECT COUNT(*) FROM Table WHERE ID = @id) = 1
    BEGIN
        UPDATE Table SET Name = 'Name' WHERE ID = @id
    END
    ELSE
    BEGIN
        INSERT INTO Table (Name) VALUES ('Name');
    END
    

    【讨论】:

      【解决方案2】:

      (1) 使用语句块

      IF 
      (SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) > 5
      BEGIN
         PRINT 'There are 5 Touring-3000 bikes.'
      END
      ELSE 
      BEGIN
         PRINT 'There are Less than 5 Touring-3000 bikes.'
      END ;
      

      (2) 调用存储过程。

      DECLARE @compareprice money, @cost money 
      EXECUTE Production.uspGetList '%Bikes%', 700, 
          @compareprice OUT, 
          @cost OUTPUT
      IF @cost <= @compareprice 
      BEGIN
          PRINT 'These products can be purchased for less than 
          $'+RTRIM(CAST(@compareprice AS varchar(20)))+'.'
      END
      ELSE
          PRINT 'The prices for all products in this category exceed 
          $'+ RTRIM(CAST(@compareprice AS varchar(20)))+'.'
      

      更多例子:

      MSDN 1 MSDN 2

      【讨论】:

      • @MuhammadHani_ 先生,存储过程应该返回一个值吧?嗯,它被声明为输出?先生有输出和输出的2个参数吗?
      【解决方案3】:

      以下示例将帮助您使用IF-ELSE 实现条件语句

      CREATE PROCEDURE SetEngineerStock
      
          @EngineerId INT,
          @PartNumber CHAR(8),
          @NewUnitsHeld DECIMAL(6,2)
      AS
      
      BEGIN
      
          SET NOCOUNT ON;
      
          -- Does stock entry exist?
          IF EXISTS(SELECT * FROM EngineerStock
                    WHERE EngineerId = @EngineerId AND PartNumber = @PartNumber)
      
              -- Yes, update existing row
              UPDATE EngineerStock
              SET UnitsHeld = @NewUnitsHeld
              WHERE EngineerId = @EngineerId AND PartNumber = @PartNumber
      
          ELSE
      
              -- No, insert new row
              INSERT INTO EngineerStock
              VALUES(@EngineerId, @PartNumber, @NewUnitsHeld)
      
      END
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-23
        • 2014-02-11
        • 2015-05-04
        • 2014-10-18
        • 1970-01-01
        • 2010-10-19
        • 2011-12-09
        • 1970-01-01
        相关资源
        最近更新 更多