[英]Execute SQL Server Stored Procedure
I am very confused as to why this isn't executing the second else if statement.我很困惑为什么这不执行第二个 else if 语句。 I just need the statement to run when there is no First_name and Surname provided, but has Age.
我只需要在没有提供 First_name 和 Surname 但有 Age 时运行该语句。 It runs the first if statement, but not the second part.
它运行第一个 if 语句,但不运行第二部分。
Here is the code这是代码
ALTER PROCEDURE [PEOPLE]
(
@AGE int,
@SURNAME nvarchar(10),
@FIRST_NAME nvarchar(10)
)
AS
BEGIN
IF(@SURNAME IS NOT NULL AND @FIRST_NAME IS NOT NULL)
BEGIN
SELECT *
FROM MEMBERS
WHERE Is_Active = 1
AND (FIRST_NAME = @FIRST_NAME AND SURNAME=@SURNAME)
END
-- This else statement isn't being executed :-(
ELSE IF(@AGE <> -1 AND @FIRST_NAME='' AND @SURNAME='')
BEGIN
SELECT *
FROM MEMBERS
WHERE(AGE = @AGE)
END
END
Here is how I'm executing it:这是我执行它的方式:
exec [PEOPLE] @AGE=24, @FIRST_NAME='', @SURNAME=''
I would be grateful if someone could help.如果有人可以提供帮助,我将不胜感激。 Thanks
谢谢
The ELSE IF
, as it is, requires that both @FIRST_NAME
and @SURNAME
not be null, which is already satisfied in the IF
.事实上,
ELSE IF
要求@FIRST_NAME
和@SURNAME
都不是 null,这在IF
中已经得到满足。
You may need to rewrite the ELSE IF
like this:您可能需要像这样重写
ELSE IF
:
ELSE IF(@AGE <> -1 AND (@FIRST_NAME IS NULL OR @FIRST_NAME='') AND (@SURNAME IS NULL OR @SURNAME=''))
Try this one:试试这个:
ALTER PROCEDURE [PEOPLE]
(
@AGE int,
@SURNAME nvarchar(10),
@FIRST_NAME nvarchar(10)
)
AS
BEGIN
SELECT *
FROM MEMBERS
WHERE
(
(IsNull(@FIRST_NAME, '') <> '') AND
(IsNull(@SURNAME, '') <> '') AND
FIRST_NAME = IsNull(@FIRST_NAME, '') AND
SURNAME = IsNull(@SURNAME, '') AND
Is_Active = 1
)
OR
(
@AGE <> -1 AND
(IsNull(@FIRST_NAME, '') = '') AND
(IsNull(@SURNAME, '') = '') AND
(AGE = @AGE)
)
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.