问题描述
我正在尝试捕获我的SQL查询是否包含0行或多行。如果行数为0,则我将插入;如果行号为1,则执行更新;如果> 1,则将进行其他分析。
有没有一种方法可以查看我的查询是否导致x个结果或自动化中没有结果?
任何帮助将不胜感激。
解决方法
您可以使用if exists
和if not exists
并在插入之前检查行是否存在,或者是否有多个行。
这是一个使用if not exists
的简单示例,如果dbo.Table
上不存在该行,则会插入一行。如果该ID已经存在,则该ID将记录到错误表中。
declare @InsertID int = 5,@Name nvarchar(max) = 'some name'
if ((select count(1) from dbo.Table where ID = @InsertID) > 1) -- detect error; more than one record for an id
begin
insert into dbo.Error (ErrorID,ErrorDate)
select @InsertID,getdate()
end
else if not exists (select 1 from dbo.Table where ID = @InsertID) -- no record exists for ID,insert it
begin
insert into dbo.Table (ID,Name)
select @InsertID,@Name
else if exists (select 1 from dbo.Table where ID = @InsertID) -- update the single record
begin
update dbo.Table set Name = @Name where ID = @InsertID
end
,
A2019将SQL查询的结果作为表返回...
查询后可以有一个if语句,该语句检查返回表的行数是否> 0,然后采取相应措施。