1

使用查詢語句我想問一下如何執行條件SQL使用IF statement,像下面的例子檢查..如果在SQL

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 

回答

3

(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

+0

@MuhammadHani_先生條件語句,存儲過程應該返回正確的價值?呃,它被宣佈爲輸出?帶輸出和輸出的2個參數先生? –

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 
1

下面的例子將幫助你實現使用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