我在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
如果@phoneExtension
为NULL
且PhoneNumbers
表中的记录NULL
为PhoneExtenstion
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
答案 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)
当@phoneExtension
为NULL
时,此过滤条件基本上会被忽略。