-2

This is my SQL Server stored procedure

CREATE PROC test_sp
@id int,
@ipVal varchar(20) = null,
@browserName varchar(20) = null
as
begin
select * from users where id=@id order by id desc;
end

I want to change my where condition in this dynamically.

When @ipVal is not null, I should pass all the three parameters in Where condition. When my @ipVal is null, then I should pass only id=@id in where condition.

How to do this in SQL Server stored procedure?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Sesuraj
  • 7
  • 1
  • 8
  • 1
    Does this answer your question? [SQL add filter only if a variable is not null](https://stackoverflow.com/questions/38828272/sql-add-filter-only-if-a-variable-is-not-null) – GSerg Aug 04 '21 at 20:34

1 Answers1

0

you can chnage your where clause to this :

select * from users 
where id=@id
and (@ipVal is null or (browserName=@browserName and ipval=@ipVal))
 
eshirvana
  • 23,227
  • 3
  • 22
  • 38