Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

While I am searching through my database, I run an INSERT statement if I find that a particular item does not exist, and I run a different INSERT statement if I find one or more of this item.

I am not entirely sure how to use the IF ELSE expressions.

What I have so far is a statement that will count the number of times the target data appears; it will print TRUE if it is greater than 0, if not, it will print FALSE. I can't find any examples to help me understand how I can use this to run two different INSERT statements.

Here is what I have so far:

SELECT CASE WHEN COUNT(*)>0 THEN 'TRUE' ELSE 'FALSE' END (   SELECT [Some Column], COUNT(*) TotalCount   FROM INCIDENTS   WHERE [Some Column] = 'Target Data'   GROUP BY [Some Column] ) 
like image 435
user1934821 Avatar asked Dec 28 '12 15:12

user1934821


People also ask

How do you use count in if condition in SQL?

SELECT [DISTINCT] COUNT([DISTINCT] IF(<condition>, <expression>, NULL)) AS alias_name FROM your_table_name; The syntax shows that: COUNT() function includes IF() function, which has a condition specified. If the <condition> is true, then the count will be calculated based on <expression> passed.

Can we use if else in stored procedure?

The IF ELSE statement controls the flow of execution in SQL Server. It can be used in stored-procedures, functions, triggers, etc. to execute the SQL statements based on the specified conditions. Boolean_expression: A boolean expression that returns TRUE or FALSE.

How do you print in SQL?

Declare @SumVal int; Select @SumVal=Sum(Amount) From Expense; Print @SumVal; You can, of course, print any number of fields from the table in this way. Of course, if you want to print all of the results from a query that returns multiple rows, you'd just direct your output appropriately (e.g. to Text).


1 Answers

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

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

Or a bit longer

DECLARE @retVal int  SELECT @retVal = COUNT(*)  FROM TABLE WHERE COLUMN = 'Some Value'  IF (@retVal > 0) BEGIN     --INSERT SOMETHING END ELSE BEGIN     --INSERT SOMETHING ELSE END  
like image 184
sgeddes Avatar answered Sep 28 '22 06:09

sgeddes