我正在编写一个带有 3 个参数的存储过程,并且我的 where 子句根据这些参数之一而改变。是否可以用这种方式编写 SQL 查询 -
CREATE PROCEDURE [dbo].[VendorVettingModal] @column NVarchar (50), @applicanttype NVarchar (10), @donotuse int AS
declare @column NVarchar (50), @applicanttype NVarchar (10), @donotuse int
select a.Id, a.Firstname, rs.Status,cs.ClearanceStatus
from applicant a
left join ReviewStatus rs on a.ReviewStatus = rs.Id
left join ClearanceStatus cs on a.ClearanceStatus = cs.Id
where
if(@column = 'Recruiting')
begin
a.applicanttype = @applicanttype and a.reviewstatus = 7 and a.donotuse = @donotuse
end
else if(@column = 'Clearance')
begin
a.applicanttype = @applicanttype and (a.reviewstatus != 7 or a.reviewstatus is null) and a.donotuse = @donotuse
end
而不是这样写?因为我有大约 20-25 列和更多的连接和参数,而不是这里定义的。我只是试图在这里让它变得不那么复杂。
CREATE PROCEDURE [dbo].[VendorVettingModal] @column NVarchar (50), @applicanttype NVarchar (10), @donotuse int AS
declare @column NVarchar (50), @applicanttype NVarchar (10), @donotuse int
if(@column = 'Recruiting')
begin
select a.Id, a.Firstname, rs.Status,cs.ClearanceStatus
from applicant a
left join ReviewStatus rs on a.ReviewStatus = rs.Id
left join ClearanceStatus cs on a.ClearanceStatus = cs.Id
where
a.applicanttype = @applicanttype and a.reviewstatus = 7 and a.donotuse = @donotuse
end
else if(@column = 'Clearance')
begin
select a.Id, a.Firstname, rs.Status,cs.ClearanceStatus
from applicant a
left join ReviewStatus rs on a.ReviewStatus = rs.Id
left join ClearanceStatus cs on a.ClearanceStatus = cs.Id
where
a.applicanttype = @applicanttype and (a.reviewstatus != 7 or a.reviewstatus is null) and a.donotuse = @donotuse
end