Discussion:
Case question
(too old to reply)
Bob
2012-06-06 00:56:27 UTC
Permalink
Can I put a sql command in the "Then" part of a Case ?

Something like this:

Case @MIY
When 0 Then Update dbo.EMI Set fieldA=@insertString Where CID=@CID
When 1 Then Update dbo.EMI Set
fieldB=@insertString Where CID=@CID
When 0 Then Update dbo.EMI Set
fieldC=@insertString Where CID=@CID
When 1 Then Update dbo.EMI Set
fieldD=@insertString Where CID=@CID
End
Jeroen Mostert
2012-06-06 05:01:55 UTC
Permalink
Post by Bob
Can I put a sql command in the "Then" part of a Case ?
No. Case is for expressions, not statements.
Post by Bob
When 1 Then Update dbo.EMI Set
When 0 Then Update dbo.EMI Set
When 1 Then Update dbo.EMI Set
End
You'll have to do this with regular IF... ELSE IF statements. It is possible
to do it in one UPDATE statement (SET fieldA = CASE WHEN @MIY = 0 THEN @CID
ELSE fieldA END etcetera), but this exercise is more academic than useful
(the result is both less readable and harder on the optimizer).
--
J.
Bob Barrows
2012-06-06 13:23:46 UTC
Permalink
Post by Bob
Can I put a sql command in the "Then" part of a Case ?
When 1 Then Update dbo.EMI Set
When 0 Then Update dbo.EMI Set
When 1 Then Update dbo.EMI Set
End
Update dbo.EMI
Set
fieldA = CASE @MIY WHEN 0 THEN @insertstring ELSE fieldA END
,fieldB = CASE @MIY WHEN 1 THEN @insertstring ELSE fieldB END
,fieldC = CASE @MIY WHEN 0 THEN @insertstring ELSE fieldC END
,fieldD = CASE @MIY WHEN 1 THEN @insertstring ELSE fieldD END
WHERE CID = @CID

It looks pretty readable to me, but it is likely to be more efficient to do:

IF @MIY = 0
Update dbo.EMI
Set
fieldA = @insertstring
,fieldC = @insertstring
WHERE CID = @CID
IF @MIY = 1
Update dbo.EMI
Set
fieldB = @insertstring
,fieldD = @insertstring
WHERE CID = @CID

It seems like a strange thing to want to do - I assume it's just for the
sake of an example ...

Loading...