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]
)
There are many, many ways to code this, but here is one possible way. I'm assuming MS SQL
We'll start by getting row count (Another Quick Example) and then do if/else
Now we can do the If / Else Logic MSDN Docs
Another faster way (inspired by Mahmoud Gamal's comment):
Forget the whole variable creation / assignment - look up "EXISTS" - MSDN Docs 2.
As long as you need to find it based on Count just more than 0, it is better to use EXISTS like this:
Depending on your needs, here are a couple of ways:
Or a bit longer
Not very clear what you mean by
. Is it using
CASE
like aSWITCH
you are after?one obvious solution is to run 2 separate queries, first select all items that have count=1 and run your insert, then select the items with count>1 and run the second insert.
as a second step if the two inserts are similar you can probably combine them into one query.
another possibility is to use a cursor to loop thru your recordset and do whatever logic you need for each line.
IF exists