我有一个存储过程,它将有3个参数。我想检查Null / Not Null的每个组合,而不是用Else写出16个不同的Select语句如果条件我怎么能写它?这是我目前的例子......
...
ELSE IF @team IS NOT NULL AND
@position IS NULL AND
@filter IS NOT NULL
BEGIN
SELECT P1.PlayerKey, P1.Player, P2.Position, P1.Height, P1.Weight, P1.Speed, P1.Status
FROM Player AS P1
INNER JOIN Position AS P2 ON P1.PositionID = P2.PositionID
INNER JOIN Team AS T1 ON T1.TeamID = P1.TeamID
WHERE P1.TeamID = @team AND P1.Player LIKE '%' + @filter + '%'
ORDER BY P2.PosSort;
END
ELSE IF @team IS NULL AND
@position IS NOT NULL AND
@filter IS NOT NULL
BEGIN
SELECT P1.PlayerKey, P1.Player, P2.Position, P1.Height, P1.Weight, P1.Speed, P1.Status
FROM Player AS P1
INNER JOIN Position AS P2 ON P1.PositionID = P2.PositionID
INNER JOIN Team AS T1 ON T1.TeamID = P1.TeamID
WHERE P2.Position = @position AND P1.Player LIKE '%' + @filter + '%'
ORDER BY P2.PosSort;
END
ELSE IF @team IS NOT NULL AND
@position IS NULL AND
@filter IS NOT NULL
BEGIN
SELECT P1.PlayerKey, P1.Player, P2.Position, P1.Height, P1.Weight, P1.Speed, P1.Status
FROM Player AS P1
INNER JOIN Position AS P2 ON P1.PositionID = P2.PositionID
INNER JOIN Team AS T1 ON T1.TeamID = P1.TeamID
WHERE P1.TeamID = @team AND P1.Player LIKE '%' + @filter + '%'
ORDER BY P2.PosSort;
END
...
答案 0 :(得分:2)
SELECT
P1.PlayerKey, P1.Player, P2.Position, P1.Height, P1.Weight, P1.Speed, P1.Status
FROM Player AS P1
INNER JOIN Position AS P2
ON P1.PositionID = P2.PositionID
INNER JOIN Team AS T1
ON T1.TeamID = P1.TeamID
WHERE (@team IS NULL OR P1.TeamID = @team)
AND (@filter IS NULL OR P1.Player LIKE '%' + @filter + '%')
AND (@position IS NULL OR P2.Position = @position)
ORDER BY P2.PosSort;