子查询语句失败时默认为一个值?

Default to a value when a sub-query statement fails?

我有以下查询:

    INSERT  INTO dbo.ResourceOrderCustomersOrders
            ( OrderId ,
              Type ,
              CustomerId ,
              ResourceId ,
              Quantity ,
              Created ,
              CreatedBy             
            )
    VALUES  ( ( SELECT  MAX(OrderId) + 1
                FROM    dbo.ResourceOrderCustomersOrders
              ) , -- OrderId - int
              'PENDING' , -- Type - varchar(50)
              ( SELECT  MAX(CustomerId)
                FROM    dbo.ResourceOrderCustomers
                WHERE   UPPER(FirstName) = UPPER(@Firstname)
                        AND UPPER(Surname) = UPPER(@Surname)
                        AND UPPER(Email) = UPPER(@Email)
              ) , -- CustomerId - int
              ( SELECT  MAX(ResourceId)
                FROM    dbo.ResourceOrderFormContent
                WHERE   DisplayTitle = @ResourceName
              ) , -- ResourceId - int
              @ResourceQuantity ,
              GETDATE() , -- Created - datetime
              'WebsiteForm' -- CreatedBy - varchar(20)

            );

在子查询失败的情况下,我想默认为我选择的值(以保存未指定的记录)。

例如,以下是否因为记录不存在而未能检索到结果:

SELECT  MAX(ResourceId)
FROM    dbo.ResourceOrderFormContent
WHERE   DisplayTitle = @ResourceName

然后我想return号码'999'(未指定记录)。解决这个问题的最佳方法是什么?

我尝试使用 try / catch,但有人告诉我这是无效语法。这是我的尝试:

    INSERT  INTO dbo.ResourceOrderCustomersOrders
            ( OrderId ,
              Type ,
              CustomerId ,
              ResourceId ,
              Quantity ,
              Created ,
              CreatedBy             
            )
    VALUES  ( ( SELECT  MAX(OrderId) + 1
                FROM    dbo.ResourceOrderCustomersOrders
              ) , -- OrderId - int
              'PENDING' , -- Type - varchar(50)
              ( SELECT  MAX(CustomerId)
                FROM    dbo.ResourceOrderCustomers
                WHERE   UPPER(FirstName) = UPPER(@Firstname)
                        AND UPPER(Surname) = UPPER(@Surname)
                        AND UPPER(Email) = UPPER(@Email)
              ) , -- CustomerId - int
              ( BEGIN TRY
                    SELECT  MAX(ResourceId)
                    FROM    dbo.ResourceOrderFormContent
                    WHERE   DisplayTitle = @ResourceName
                END TRY
                BEGIN CATCH
                    SELECT 999
                END CATCH
              ) , -- ResourceId - int
              @ResourceQuantity ,
              GETDATE() , -- Created - datetime
              'WebsiteForm' -- CreatedBy - varchar(20)

            );
如果找不到行,

Max 将始终 return NULL。所以你可以使用 ISNULL.

SELECT  ISNULL(MAX(ResourceId), 999)
FROM    dbo.ResourceOrderFormContent
WHERE   DisplayTitle = @ResourceName