我想要的是当@AddressCode为null时只需执行

SELECT
    *
FROM
    Addresses
WHERE
    1= 1

如果@AddressCode不为NULL,则执行
SELECT
    *
FROM
    Addresses
WHERE
    1= 1 AND @AddressCode=Addresses.AddressCode

我该如何实现呢?我在下面尝试了查询,但对于带NULL值的地址或@AddressCode is NULL ...时,它不起作用。
Declare @AddressCode varchar(20)
Set @AddressCode=NULL

SELECT
    *
FROM
    Addresses
WHERE
    1= 1
    AND
    CASE @AddressCode
        WHEN NULL
        THEN Addresses.AddressCode
        ELSE @AddressCode
    END =Addresses.AddressCode

我努力了,但没有做到……我知道我可以写IF语句并写单个select语句,但是我不想这样做,因为我有很多类似@AddressCode的标准:(

最佳答案

SELECT *
FROM
    Addresses
WHERE
    (@AddressCode IS NULL OR Addresses.AddressCode = @AddressCode)

10-05 21:18