Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

sql - 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]
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...