2010-01-18 67 views
5

有沒有辦法做到這一點較短,例如在Transact-sql中使用某種條件運算符?Transact-sql中的條件運算符

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

UPDATE BinaryAssets.BinaryAssetStructures 
SET  ParentBinaryAssetStructureId = @ParentBinaryAssetStructureId 
WHERE BinaryAssetStructureId = @OriginalBinaryAssetStructureId 

回答

7

使用NULLIF()

UPDATE BinaryAssets.BinaryAssetStructures 
SET  ParentBinaryAssetStructureId = NULLIF(@ParentBinaryAssetStructureId,-1) 
WHERE BinaryAssetStructureId = @OriginalBinaryAssetStructureId 
2
UPDATE BinaryAssets.BinaryAssetStructures 
SET  ParentBinaryAssetStructureId = 
    CASE ParentBinaryAssetStructureId 
    WHEN -1 THEN NULL 
    ELSE ParentBinaryAssetStructureId 
    END 
WHERE BinaryAssetStructureId = @OriginalBinaryAssetStructureId 

給一個掄

4

三元(條件)運算符在C一樣的語言:

x = doSomething ? 5 : 7 

會這樣寫在SQL中:

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

可以有多個的情況下(當子句):

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