There are several solutions, I will mention 3 of them.
In the examples below, I check if the variable @idUsuario
is null if it does not search the user name with the idUsuario
corresponding to the variable.
Alternative to CASE WHEN :
DECLARE @idUsuario INT
SET @idUsuario = 1
SELECT
Nome
FROM
Usuario
WHERE
idUsuario = (
CASE WHEN @idUsuario IS NULL THEN
idUsuario
ELSE
@idUsuario
END
)
Alternative with Value Comparison and logical operator use OR to form the filter:
DECLARE @idUsuario INT
SET @idUsuario = 1
SELECT
Nome
FROM
Usuario
WHERE
(@idUsuario IS NULL OR idUsuario = @idUsuario)
Alternative with dynamic query :
DECLARE @query varchar(MAX)
DECLARE @idUsuario INT
SET @idUsuario = 1
SET @query = 'SELECT Nome FROM Usuario'
IF @idUsuario IS NOT NULL
BEGIN
SET @query = @query + ' WHERE idUsuario =' + CONVERT(VARCHAR(MAX), @idUsuario)
END
EXEC (@query)