SQL - 计算返回的记录

时间:2010-02-12 21:07:44

标签: sql

我正在构建一个存储过程。如果不存在具有特定值的记录,则此存储过程需要插入记录。如果值确实存在,我需要更新记录。我遇到的问题是确定是否存在具有给定值的记录。我使用以下代码:

DECLARE @record1ID as char(36)
SET @record1ID = (SELECT TOP 1 ID FROM Person WHERE [Role]='Manager')

DECLARE @record2ID as char(36)
SET @record2ID = (SELECT TOP 1 d.ID FROM Department d WHERE d.[ManagerID]=@record1ID)

-- If @record2ID is set update record, otherwise add record 
-- how do I setup this if/else statement?

谢谢!

2 个答案:

答案 0 :(得分:1)

如果这是一个SQL Server,你可以像这样计算:

将@rec_counter声明为int

设置@rec_counter = 0

选择@rec_counter = count(*)FROM Department d WHERE d。[ManagerID] = @ record1

if(@rec_counter> 0)

开始

-- do whatever here

答案 1 :(得分:0)

IF (EXISTS YOUR_SELECT)
BEGIN ...

IF (@record2ID IS NULL) 
BEGIN ...

或使用select count(*)代替选择值