Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator in Transact-sql

Tags:

sql

sql-server

Is there a way to do this shorter, for instance using some sort of conditional operator in Transact-sql?

IF @ParentBinaryAssetStructureId = -1
BEGIN
    SET @ParentBinaryAssetStructureId = NULL
END

UPDATE  BinaryAssets.BinaryAssetStructures 
SET     ParentBinaryAssetStructureId = @ParentBinaryAssetStructureId
WHERE   BinaryAssetStructureId = @OriginalBinaryAssetStructureId
like image 491
Lieven Cardoen Avatar asked Jan 18 '10 20:01

Lieven Cardoen


3 Answers

USE NULLIF()

UPDATE  BinaryAssets.BinaryAssetStructures 
SET     ParentBinaryAssetStructureId = NULLIF(@ParentBinaryAssetStructureId,-1)
WHERE   BinaryAssetStructureId = @OriginalBinaryAssetStructureId
like image 86
Paul Creasey Avatar answered Oct 07 '22 03:10

Paul Creasey


The ternary (conditional) operator in c like languages:

x = doSomething ? 5 : 7

would be written like this in SQL:

SELECT @x = CASE WHEN @doSomething = 1 THEN 5 ELSE 0 END

There can be multiple cases (when clauses):

SELECT @x = CASE WHEN @doSomething = 1 THEN 5 WHEN @somethingElse = 1 THEN 20 ELSE 0 END
like image 21
sphereinabox Avatar answered Oct 07 '22 04:10

sphereinabox


UPDATE  BinaryAssets.BinaryAssetStructures 
SET     ParentBinaryAssetStructureId =
   CASE  ParentBinaryAssetStructureId  
     WHEN -1 THEN NULL
     ELSE ParentBinaryAssetStructureId
   END
WHERE   BinaryAssetStructureId = @OriginalBinaryAssetStructureId

Give that a whirl

like image 28
Jeff Ferland Avatar answered Oct 07 '22 03:10

Jeff Ferland