存储过程中的SQL条件连接(带/不带参数)

时间:2012-02-03 06:44:26

标签: sql sql-server-2005

我正在使用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起作用?获得预期结果的最佳方法是什么?

1 个答案:

答案 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))

虽然不是最干净的,但却有效。