tags:

views:

58

answers:

3

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
+5  A: 

USE NULLIF()

UPDATE  BinaryAssets.BinaryAssetStructures 
SET     ParentBinaryAssetStructureId = NULLIF(@ParentBinaryAssetStructureId,-1)
WHERE   BinaryAssetStructureId = @OriginalBinaryAssetStructureId
Paul Creasey
Cool. Thx. Clearly a winner.
Lieven Cardoen
+1  A: 
UPDATE  BinaryAssets.BinaryAssetStructures 
SET     ParentBinaryAssetStructureId =
   CASE  ParentBinaryAssetStructureId  
     WHEN -1 THEN NULL
     ELSE ParentBinaryAssetStructureId
   END
WHERE   BinaryAssetStructureId = @OriginalBinaryAssetStructureId

Give that a whirl

Autocracy
+1  A: 

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
sphereinabox