I want to create a procedure which returns a table on the basis of input of parmeters as fields and operator …how can I use operator selection which is passed as a parameter string
ALTER PROCEDURE dbo.sp_getStaffRecord
(
@deptname varchar(50),
@dob date,
@active bit,
@salary int,
@firstname varchar(50),
@lastname varchar(50),
@OperatorDob varchar(2),
@OperatorSalary varchar(2)
)
AS
select
st.id, firstname, lastname, deptname, salary, dob,
(select firstname + ', ' + lastname from StaffTable
where firstname = @firstname and lastname = @lastname) as [Reporting To],
doj, active
from
StaffTable st
inner join
DepartmentTable dt on dt.id = st.dept
where
dt.deptname = @deptname
and
(
if (@OperatorDob = '>=')
st.dob >= @dob
else if (@OperatorDob = '<=')
st.dob <= @dob
else if (@OperatorDob = '=')
st.dob = @dob
else if (@OperatorDob = '>')
st.dob > @dob
else if (@OperatorDob = '<=')
st.dob = @dob
)
and st.active = @active
and st.salary >= @salary
RETURN
You can’t use
IF..ELSEthe way you want to. What you can do is combine the value of the@OperatorDobwith the logic it should execute:If the
@OperatorDobvalue happens not to be any of those specified above (e.g.'!=') then the query won’t produce any results. This might be a desirable side-effect.