Как осуществлять фильтрацию по четырем переменным, при условии, что в некоторых может не быть значений (если переменная равна нулю, столбец должен отображать все данные)?
Строковой переменной "@lastName" можно присвоить '%' и тогда столбец будет выводить все данные, а как быть с переменными Int?
Declare @statusNumbers Int, @departmentNumbers Int, @postNumber Int, @lastName Varchar(100)
Set @statusNumbers = ?
Set @departmentNumbers = ?
Set @postNumber = ?
Set @lastName = '%'
Select Persons.Id, Persons.LastName, Persons.FirstName, Persons.SecondName, Statuses.Id, Statuses.Name as Status, Deps.Id, Deps.Name as Department, Posts.Id, Posts.Name as Post, Persons.DateEmploy as Employ, Persons.DateUnemploy as Unemploy
From dbo.Persons
Join dbo.Statuses on Statuses.Id = Persons.StatusId
Join dbo.Deps on Deps.Id = Persons.DepId
Join dbo.Posts on Posts.Id = Persons.PostId
Where Persons.StatusId = @statusNumbers and
Persons.DepId = @departmentNumbers and
Persons.PostId = @postNumber and
LastName Like '%' + RTRIM(@lastName) + '%'
Согласно комментарию и ссылки, нужно было:
Инициализировать переменные:
Declare @statusNumbers Int = null, @departmentNumbers Int = null, @postNumber Int = null, @lastName Varchar(100) = '%'
Изменить условие в 'Where':
Where (Persons.StatusId = @statusNumbers or @statusNumbers is null) and (Persons.DepId = @departmentNumbers or @departmentNumbers is null) and (Persons.PostId = @postNumber or @postNumber is null) and LastName Like '%' + RTRIM(@lastName) + '%'
Проверив перебором переменных, все работает.
(Persons.StatusId = @statusNumbers OR @statusNumbers IS NULL)