谁能告诉我这有什么问题?我实际上试图在表中搜索空值,如果可能的话,建议我这样做的有效方法

问题描述 投票:-3回答:2
CREATE FUNCTION UDF_MALEEMPLOYEES(@GENDER NVARCHAR(4))
RETURNS TABLE
AS RETURN
IF (@GENDER='NULL')
(SELECT CONCAT(FIRSTNAME, CASE WHEN MIDDLENAME IS NULL THEN ' ' ELSE ' ' +MIDDLENAME+' ' END,LASTNAME) 
AS FULLNAME, CAST(BIRTHDATE AS DATE) AS BIRTHDATE,GENDER FROM PERSON.PERSON
A INNER JOIN [Sales].[vPersonDemographics] B ON A.BUSINESSENTITYID = B.BUSINESSENTITYID 
WHERE GENDER IS NULL)
ELSE
(SELECT CONCAT(FIRSTNAME, CASE WHEN MIDDLENAME IS NULL THEN ' ' ELSE ' ' +MIDDLENAME+' ' END,LASTNAME) 
AS FULLNAME, CAST(BIRTHDATE AS DATE) AS BIRTHDATE,GENDER FROM PERSON.PERSON
A INNER JOIN [Sales].[vPersonDemographics] B ON A.BUSINESSENTITYID = B.BUSINESSENTITYID 
WHERE GENDER =@GENDER)
sql-server
2个回答
0
投票

Null不能等于null。您必须使用IS NULL,如下所示

CREATE FUNCTION UDF_MALEEMPLOYEES(@GENDER NVARCHAR(4))
RETURNS TABLE
AS RETURN
IF (@GENDER IS NULL)
(SELECT CONCAT(FIRSTNAME, CASE WHEN MIDDLENAME IS NULL THEN ' ' ELSE ' ' +MIDDLENAME+' ' END,LASTNAME) 
AS FULLNAME, CAST(BIRTHDATE AS DATE) AS BIRTHDATE,GENDER FROM PERSON.PERSON
A INNER JOIN [Sales].[vPersonDemographics] B ON A.BUSINESSENTITYID = B.BUSINESSENTITYID 
WHERE GENDER IS NULL)
ELSE
(SELECT CONCAT(FIRSTNAME, CASE WHEN MIDDLENAME IS NULL THEN ' ' ELSE ' ' +MIDDLENAME+' ' END,LASTNAME) 
AS FULLNAME, CAST(BIRTHDATE AS DATE) AS BIRTHDATE,GENDER FROM PERSON.PERSON
A INNER JOIN [Sales].[vPersonDemographics] B ON A.BUSINESSENTITYID = B.BUSINESSENTITYID 
WHERE GENDER =@GENDER)

0
投票

当与NULL比较时,你使用IS NULL,而不是='NULL',因为最后一个是varchar文字。

您还可以使您的功能更容易,更易于维护,如下所示:

CREATE FUNCTION UDF_MALEEMPLOYEES(@GENDER NVARCHAR(4))
RETURNS TABLE
AS RETURN
SELECT 
    CONCAT(FIRSTNAME, CASE WHEN MIDDLENAME IS NULL THEN ' ' ELSE ' ' +MIDDLENAME+' ' END,LASTNAME) AS FULLNAME, 
    CAST(BIRTHDATE AS DATE) AS BIRTHDATE,
    GENDER 
FROM 
    PERSON.PERSON A 
    INNER JOIN [Sales].[vPersonDemographics] B ON A.BUSINESSENTITYID = B.BUSINESSENTITYID 
WHERE 
    ISNULL(GENDER, '') = ISNULL(@GENDER, '')
© www.soinside.com 2019 - 2024. All rights reserved.