Using IF ELSE statement based on Count to execute different Insert statements Using IF ELSE statement based on Count to execute different Insert statements sql sql

Using IF ELSE statement based on Count to execute different Insert statements


Depending on your needs, here are a couple of ways:

IF EXISTS (SELECT * FROM TABLE WHERE COLUMN = 'SOME VALUE')    --INSERT SOMETHINGELSE    --INSERT SOMETHING ELSE

Or a bit longer

DECLARE @retVal intSELECT @retVal = COUNT(*) FROM TABLEWHERE COLUMN = 'Some Value'IF (@retVal > 0)BEGIN    --INSERT SOMETHINGENDELSEBEGIN    --INSERT SOMETHING ELSEEND 


As long as you need to find it based on Count just more than 0, it is better to use EXISTS like this:

IF EXISTS (SELECT 1 FROM INCIDENTS  WHERE [Some Column] = 'Target Data')BEGIN    -- TRUE ProcedureENDELSE BEGIN    -- FALSE ProcedureEND


Simply use the following:

IF((SELECT count(*) FROM table)=0)BEGIN....END