我正在編寫一個帶有3個參數的存儲過程,而且where子句根據其中一個參數進行更改。是否有可能以這種方式編寫SQL查詢 -若要在存儲過程中的where子句中使用
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列和更多的連接,並且在這裏定義了params。我只是試圖讓它在這裏變得更簡單。
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
你也許可以改善它有點通過分解'a.applicanttype = @ applicanttype'和'a.donotuse = @donotuse' –
@ConradFrix良好的呼叫,更新超過 – msmucker0527
msmucker0527:真棒作品就像我想要的,其實我還有一個,如果在if (@column ='Recruiting') 但我可以使用paranthesis來實現它。 – sarsha