我正在使用SQL Server 2005中的存储过程。如果只有参数不为null,是否可以使用连接?以下是查询示例:
ALTER PROCEDURE [dbo].[SPSample]
@gender varchar(20) = null
@username varchar(20) = null
AS
SELECT
per.firstName,
per.lastName,
per.gender
FROM person per
INNER JOIN account ac on ac.idPerson = per.idPerson
WHERE (
gender = @gender
AND (@username is null or (@username is not null and @username = acc.username))
如果INNER JOIN
不为空,如何使@username
起作用?获得预期结果的最佳方法是什么?
答案 0 :(得分:2)
ALTER PROCEDURE [dbo].[SPSample]
@gender varchar(20) = null
@username varchar(20) = null
AS
SELECT
per.firstName,
per.lastName,
per.gender
FROM person per
LEFT JOIN account ac
ON @username is not null
AND @username = ac.username
AND ac.idPerson = per.idPerson
WHERE --(
gender = @gender
--AND (@username is null or (@username is not null and @username = acc.username))
虽然不是最干净的,但却有效。