我刚刚开始学习SQL,如果您能帮助SELECT查询,将非常感谢。有输入变量:@p_IPN
和@p_SecondName
,该表具有SECONDNAME
,FIRSTNAME
,MIDDLENAME
和IPN
列。
我需要在以下条件下通过指定的输入字符在表中进行搜索:
如果未指定任何变量,则查询应返回整个表;
如果指定了@p_IPN
或@p_SecondName
,则查询应按IPN LIKE @p_IPN OR SECONDNAME LIKE @p_SecondName
执行搜索;
如果同时指定了两个变量,则查询应返回输入字符为@p_IPN
和@p_SecondName
(IPN LIKE @p_IPN AND SECONDNAME LIKE @p_SecondName
)的行
我使用了以下查询:
IF (@p_IPN IS NULL AND @p_SecondName IS NULL)
SELECT
CAST(IPN AS NVARCHAR(MAX)) AS IPN, FIRSTNAME, SECONDNAME, MIDDLENAME
FROM
dbo.BE_BlackList
ELSE IF (@p_IPN IS NULL)
SELECT
CAST(IPN AS NVARCHAR(MAX)) AS IPN, FIRSTNAME, SECONDNAME, MIDDLENAME
FROM
dbo.BE_BlackList
WHERE
SECONDNAME LIKE @p_SecondName
ELSE IF (@p_SecondName IS NULL)
SELECT
CAST(IPN AS NVARCHAR(MAX)) AS IPN, FIRSTNAME, SECONDNAME, MIDDLENAME
FROM
dbo.BE_BlackList
WHERE
IPN LIKE @p_IPN
ELSE
SELECT
CAST(IPN AS NVARCHAR(MAX)) AS IPN, FIRSTNAME, SECONDNAME, MIDDLENAME
FROM
dbo.BE_BlackList
WHERE
IPN LIKE @p_IPN AND SECONDNAME LIKE @p_SecondName
它运作良好,但是,我仍然需要使用SELECT查询获得相同的结果。
我尝试过:
SELECT CASE WHEN @p_IPN IS NULL AND @p_Secondname IS NULL THEN
(SELECT cast (IPN AS nvarchar(max)) AS IPN, FIRSTNAME, MIDDLENAME, SECONDNAME FROM dbo.BE_BlackList)
WHEN @p_SecondName IS NULL THEN
(SELECT cast(IPN AS nvarchar(max)) AS IPN, FIRSTNAME, MIDDLENAME, SECONDNAME FROM dbo.BE_BlackList
WHERE IPN LIKE @p_IPN)
WHEN @p_IPN IS NULL THEN
(SELECT cast(IPN AS nvarchar(max)) AS IPN, FIRSTNAME, MIDDLENAME, SECONDNAME FROM dbo.BE_BlackList
WHERE SECONDNAME LIKE @p_Secondname)
ELSE
(SELECT cast (IPN AS nvarchar(max)) AS IPN, FIRSTNAME, MIDDLENAME, SECONDNAME FROM dbo.BE_BlackList
WHERE SECONDNAME LIKE @p_Secondname AND IPN LIKE @p_IPN)
END
FROM dbo.BE_BlackList
我收到此错误:
第16层,状态1,第10行,Msg 116
如果未使用EXISTS引入子查询,则只能在选择列表中指定一个表达式。
我不确定如何在这里使用CASE WHEN EXISTS
(如果可能的话)。你能帮忙吗?
答案 0 :(得分:3)
您可以将WHERE用作条件过滤器,而不是使用IF ELSE
SELECT
CAST(IPN AS NVARCHAR(MAX)) AS IPN, FIRSTNAME, SECONDNAME, MIDDLENAME
FROM
dbo.BE_BlackList
WHERE
(@p_IPN IS NULL OR IPN LIKE @p_IPN)
AND
(@p_SecondName IS NULL OR SECONDNAME LIKE @p_SecondName)
答案 1 :(得分:0)
问题出在您的CASE WHEN
语法上。将CASE WHEN
视为一列。换句话说,SELECT CASE WHEN a = b, THEN c FROM dbo.BE_BlackList
您在说SELECT CASE WHEN a = b then SELECT c from dbo.BE_Blacklist
-注意,这里有两个选择语句。