使用基于Count的IF ELSE语句执行不同的Insert语句 [英] Using IF ELSE statement based on Count to execute different Insert statements
问题描述
当我在我的数据库中搜索时,如果我发现某个特定项目不存在,我会运行一个 INSERT 语句,如果我找到一个或多个这个项目,我会运行一个不同的 INSERT 语句.
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.
我不完全确定如何使用 IF ELSE 表达式.
I am not entirely sure how to use the IF ELSE expressions.
我目前得到的是一个语句,它会统计目标数据出现的次数;如果大于 0 则打印 TRUE,否则打印 FALSE.我找不到任何示例来帮助我理解如何使用它来运行两个不同的 INSERT 语句.
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.
这是我目前所拥有的:
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]
)
推荐答案
根据您的需要,这里有几种方法:
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
或者更长一点
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
这篇关于使用基于Count的IF ELSE语句执行不同的Insert语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!