如果结果集为空,请填写基本值

时间:2014-08-26 10:29:33

标签: sql

如果查询的结果集为空,我想强制执行特定的结果。

当我使用下面的查询时,我只会在有结果时得到答案。

如果结果不存在,我希望查询通过询问字段(@ProductheaderdoscodeBOM)返回结果'NONE'

查看查询:

USE [DM]
GO
/****** Object:  StoredProcedure [dbo].[SIP_rpt_R9000_PD_BOM]    Script Date:     08/26/2014 11:04:25 ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

ALTER PROCEDURE [dbo].[SIP_rpt_R9000_PD_BOM]
     @ProdHeaderDossierCode T_Code_ProdHeadDossier = NULL,
     @ProductheaderdoscodeBOM T_Code_ProdHeadDossier = NULL
AS
BEGIN
    SET NOCOUNT ON;
    SELECT @ProductheaderdoscodeBOM=PHPL.ProdHeaderDossierCode 
    FROM T_ProdHeadProdBomLink as PHPL
    WHERE PHPL.ProdBOMProdHeaderDossierCode=@ProdHeaderDossierCode
    IF @@ROWCOUNT=0
    SET @ProductheaderdoscodeBOM='NONE'
    SELECT @ProductheaderdoscodeBOM
    FROM T_ProdHeadProdBomLink as PHPL
    WHERE PHPL.ProdBOMProdHeaderDossierCode=@ProdHeaderDossierCode
    RETURN 0
END`

1 个答案:

答案 0 :(得分:2)

如果我理解正确,您只想在第一个查询没有返回任何行时返回'NONE'。我认为这个逻辑会做你想要的:

select @ProductheaderdoscodeBOM = PHPL.ProdHeaderDossierCode 
FROM T_ProdHeadProdBomLink as PHPL
WHERE PHPL.ProdBOMProdHeaderDossierCode = @ProdHeaderDossierCode;

if @@ROWCOUNT = 0 begin
    set @ProductheaderdoscodeBOM = 'NONE';
end;

select @ProductheaderdoscodeBOM;
return 0;

换句话说,您不需要重复查询。

顺便说一句,您也可以在没有if

的情况下执行此操作
select @ProductheaderdoscodeBOM = coalesce(max(PHPL.ProdHeaderDossierCode), 'NONE')
FROM T_ProdHeadProdBomLink as PHPL
WHERE PHPL.ProdBOMProdHeaderDossierCode = @ProdHeaderDossierCode;

select @ProductheaderdoscodeBOM;