您好我被困在以下存储过程中。这是我想要做的。
我有两个表:TableA和TableB。
我知道在此程序中可以应用if存在或不存在的位置;但我只是不知道如何成功地做到这一点。代码如下。我很感激你的时间。非常感谢你
P.S。错误是通知hmi如果tableA和tableB没有现有的silo,slow和close,则弹出一个消息框。就这样。 仅用于验证和通知目的。
USE [Product]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Proc [Controls].[spSiloSettings]
@Silo int
,@PartNo Varchar (50)
,@Slow float output
,@Close float output
,@errorout int output
AS
if exists (select slow, close from controls.TableA where @silo = silo and @partno= partno)
set @errorout = 0
select @slow= slow, @close = close
from TableA
where @silo = silo
if not exists(select top 1 @silo = silo, @slow= slow, @close = close)
From controls.TableB
Where silo = @silo
insert into controls.TableA (silo, partno, slow, close)
values (@silo, @partno ,@slow, @close)
end
答案 0 :(得分:2)
我认为这就是你所追求的:
USE [Product]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Proc [Controls].[spSiloSettings]
@Silo int
,@PartNo Varchar (50)
,@Slow float output
,@Close float output
,@errorout int output
AS
BEGIN
declare @found bit = 0
set @errorout = 0
select @slow = slow
, @close = close
, @found = 1
from controls.TableA
where silo = @silo
and partno = @partno
if @found != 1
begin
select top 1
@found = 1
, @slow= slow
, @close = close
From controls.TableB
Where silo = @silo
--order by something to ensure consistent results?
if @found = 1
begin
insert into controls.TableA (silo, partno, slow, close)
values (@silo, @partno ,@slow, @close)
end
else
begin
@errorout = 1 --neither A nor B held the value we were after
end
end
END