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]
)
8条答案
按热度按时间slsn1g291#
Depending on your needs, here are a couple of ways:
Or a bit longer
fiei3ece2#
Simply use the following:
edqdpe6u3#
As long as you need to find it based on Count just more than 0, it is better to use EXISTS like this:
eivgtgni4#
IF exists
rjzwgtxy5#
Not very clear what you mean by
"I cant find any examples to help me understand how I can use this to run 2 different statements:"
. Is it using
CASE
like aSWITCH
you are after?cxfofazt6#
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.
f87krz0w7#
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 .
ax6ht2ek8#
If this is in SQL Server, your syntax is correct; however, you need to reference the COUNT(*) as the Total Count from your nested query. This should give you what you need:
Using this, you could assign TotalCount to a variable and then use an IF ELSE statement to execute your INSERT statements: