如何使存储过程参数向后兼容?

How to make a stored procedure parameter backwards compatible?

我有一个接受以下参数的存储过程:

@ExecutionID INT,    
@Status_Name VARCHAR(50),  

我们需要更改程序,使其接受多个 ID,而不仅仅是 ExecutionID,因此现在参数如下所示:

@Id INT, 
@Status_Name VARCHAR(50),  
@IdType BIT = 0 --0 for ExecutionID and 1 for InsertID)

SELECT TOP 1 @Status_Curent = [' + @Status_Name + '_Status] 
FROM [Database].[dbo].[StoredProcedure] 
WHERE [' + CASE WHEN COALESCE(@IdType, 0) = 0 THEN 'Execution' ELSE 'Insert' END + 'ID] = ' + CAST(@Id AS VARCHAR(50)) + ' 
ORDER BY [' + @Status_Name + '_Status] DESC

但我们还有其他项目运行旧程序。我如何才能将 @ExecutionID 默认为 运行 就好像它是 @Id 这样我们就不必更改其他项目?

到目前为止我有这个:

DECLARE @Status_Name VARCHAR(50) = 'Food',
        @IdType BIT = 0,
        @Id INT = NULL,
        @ExecutionID INT = 6045

IF (@ExecutionID != NULL)
BEGIN
    SET @Id = @ExecutionID
END

SELECT @Id

SET @Id = CASE WHEN @ExecutionID != NULL THEN @ExecutionID ELSE @Id END

但它们仍然 return NULL。

提前致谢

您不能使用通常的相等或不等运算符将变量与 NULL 进行比较 - 这些运算符总是 return NULL / undefined。

您需要专门使用 @ExecutionID IS NULL@ExecutionID IS NOT NULL - 所以试试这个:

DECLARE @Status_Name VARCHAR(50) = 'Food',
        @IdType BIT = 0,
        @Id INT = NULL,
        @ExecutionID INT = 6045

IF (@ExecutionID IS NOT NULL)
BEGIN
    SET @Id = @ExecutionID
END

SELECT @Id

SET @Id = CASE 
              WHEN @ExecutionID IS NOT NULL 
                  THEN @ExecutionID 
                  ELSE @Id 
          END