Question

I would like to ask how to perform condition checking using IF statement in SQL, something like the below examples ..

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

insert statement


else

update statement

go

or something similar like using a stored procedure...

if (exec SP_something 2012, 1) = 0 

insert statement

else

update stement

or maybe by using a UDF in the sql statement like...

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

insert statement

else

update statement

go
Was it helpful?

Solution

(1) Using a statement block

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) Calling stored procedures.

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)))+'.'

More Examples:

MSDN 1 MSDN 2

OTHER TIPS

You will want to do something like this:

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

The following example would help you to implement conditional statement using 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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top