我正在尝试捕获我的SQL查询是否有0行或多行。如果它有0行,那么我将插入,如果1将执行更新,如果>1将执行额外的分析。
有没有一种方法可以让我的查询在任何地方自动产生x个结果或没有结果?
任何帮助都将不胜感激。
发布于 2020-08-22 11:01:45
您可以使用if exists和if not exists,并在执行插入之前检查行是否存在,甚至检查行是否有多行。
下面是一个使用if not exists的简单示例,其中如果dbo.Table上不存在该行,它将插入一行。如果它已经存在,则该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发布于 2020-09-01 21:23:00
A2019以表的形式返回SQL查询的结果...
您可以在查询之后立即使用if语句,该语句检查返回的表的行数是否大于0,然后采取相应的操作。

https://stackoverflow.com/questions/63532047
复制相似问题