存储过程中的T-SQL Null比较

时间:2017-10-17 17:10:46

标签: sql sql-server tsql stored-procedures

我在SQL Server中存储过程时遇到了一些问题。我正在尝试选择一个电话号码来获取Id,但我遇到的问题是列PhoneExtension定义为int并允许空值。

以下代码有效,但可能无法返回所需的结果(可能存在具有多个扩展名的相同电话号码)

CREATE PROCEDURE [dbo].[GetPhoneNumberId]
    @phoneNumber INT,
    @phoneExtension INT = NULL,
    @countryCode INT = 1,
    @PhoneNumberId INT OUTPUT
AS
BEGIN
    SET @PhoneNumberId = (SELECT TOP 1 PhoneNumberId
                          FROM PhoneNumbers
                          WHERE PhoneNumber = @phoneNumber
                            AND PhoneCountryCode = @countryCode);
END

如果@phoneExtensionNULLPhoneNumbers表中的记录NULLPhoneExtenstion

,则下一个不起作用
CREATE PROCEDURE [dbo].[GetPhoneNumberId]
    @phoneNumber INT,
    @phoneExtension INT = NULL,
    @countryCode INT = 1,
    @PhoneNumberId INT OUTPUT
AS
BEGIN
    SET @PhoneNumberId = (SELECT TOP 1 PhoneNumberId
                          FROM PhoneNumbers
                          WHERE PhoneNumber = @phoneNumber
                            AND PhoneExtension = @phoneExtension
                            AND PhoneCountryCode = @countryCode);
END

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

CREATE PROCEDURE [dbo].[GetPhoneNumberId]
    @phoneNumber INT,
    @phoneExtension INT = NULL,
    @countryCode INT = 1,
    @PhoneNumberId INT OUTPUT
AS
BEGIN
    SET @PhoneNumberId = (SELECT TOP 1 PhoneNumberId
                          FROM PhoneNumbers
                          WHERE PhoneNumber = @phoneNumber
                            AND (ISNULL(PhoneExtension, '') = ISNULL(@phoneExtension, ''))
                            AND PhoneCountryCode = @countryCode);
END

答案 1 :(得分:1)

你可以试试这个:

CREATE PROCEDURE [dbo].[GetPhoneNumberId]
    @phoneNumber INT,
    @phoneExtension INT = NULL,
    @countryCode INT = 1,
    @PhoneNumberId INT OUTPUT
AS
BEGIN
    SET @PhoneNumberId = (SELECT TOP 1 PhoneNumberId
                          FROM PhoneNumbers
                          WHERE PhoneNumber = @phoneNumber
                            AND (
                                PhoneExtension = @phoneExtension
                                OR 
                                (PhoneExtension IS NULL AND @phoneExtension IS NULL)
                                )
                            AND PhoneCountryCode = @countryCode);
END

答案 2 :(得分:0)

更改

PhoneExtension = @phoneExtension

PhoneExtension = ISNULL(@phoneExtension, PhoneExtension)

@phoneExtensionNULL时,此过滤条件基本上会被忽略。