我有一個可以通過6個下拉框過濾的gridview,所以在編寫sql時最簡單的事情是使用'或'語句,如果下拉列表有選擇或空等我應該用什麼來代替SQL「OR」語句
但是我已閱讀這裏和其他網站使用SQL或語句是一個壞主意,任何人都可以提供任何其他建議,我可以使用,而不是我寫每個ddl選擇是否爲空的變化?下面是第一次查詢的例子,每DDL返回值
@ruleID int = null,
@engagementStatusID int = null,
@areaOfWorkID int = null,
@registered bit = null,
@staffGroupID int = null,
@assignmentTypeID int = NULL
AS
SET NOCOUNT ON
IF (@ruleID IS NOT NULL and @engagementStatusID IS NOT NULL and @areaOfWorkID IS NOT NULL and
@registered IS NOT NULL and @staffGroupID IS NOT NULL and @assignmentTypeID IS NOT NULL)
BEGIN
SELECT r.dbRuleId AS RuleID,r.dbEngagementStatusId AS EngagementStatusID,
r.dbIsAllStaffGroups AS AllStaffGroups,r.dbIsAllAssignments AS AllAssignments,
r.dbIsAllRegistered AS AllRegistered,r.dbIsAllUnregistered AS AllUnregistered,
r.dbSoftDelete AS Softdelete, es.dbName AS EngagementName,
sgc.dbName AS StaffGroupName, aow.dbName AS AreaOfWorkName,
at.dbName AS AssignmentName, at.dbIsRegistered AS Registered,sgc.dbStaffGroupCodeId AS StaffGroupCodeID,
at.dbAssignmentTypeId AS AssignmentID, aow.dbAreaOfWorkId AS AreaOfWorkID
FROM dbo.tbRule r INNER JOIN
dbo.EngagementStatus es ON r.dbEngagementStatusId = es.dbEngagementStatusId INNER JOIN
dbo.RuleStaffGroup rsg ON r.dbRuleId = rsg.dbRuleId INNER JOIN
dbo.StaffGroupCode sgc ON rsg.dbStaffGroupId = sgc.dbStaffGroupCodeId INNER JOIN
dbo.RuleAssignmentCode rac ON r.dbRuleId = rac.dbRuleId INNER JOIN
dbo.AssignmentCode ac ON
rac.dbAssignmentCodeId = ac.dbAssignmentCodeId INNER JOIN
dbo.AssignmentType at ON ac.dbAssignmentId = at.dbAssignmentTypeId INNER JOIN
dbo.AreaOfWork aow ON ac.dbAreaOfWorkId = aow.dbAreaOfWorkId
WHERE ((r.dbRuleId = @ruleID) and (r.dbEngagementStatusId = @engagementStatusID) and (aow.dbAreaOfWorkId = @areaOfWorkID) and
(at.dbIsRegistered = @registered) and (sgc.dbStaffGroupCodeId = @staffGroupID) and (at.dbAssignmentTypeId = @assignmentTypeID))
對此有何意見將是巨大的
更新 我覺得我應該澄清一些關於我的代碼,當我說空,這是我分配到「所有」選擇下拉列表中的值,因此,例如IMN大多數情況下,我做這樣的事情來獲取需要傳遞給DB
int? Type = (this.ddlType.SelectedValue.ToString() == "All") ? (int?)null : Convert.ToInt32(this.ddlType.SelectedValue.ToString());
所以價值如果用戶選擇了所有Db接收者'空'w然後我可以使用'if @blah IS NOT NULL'等。我意識到這可能不是最好的方法來做到這一點
爲什麼SQL還是一個壞主意? – Liam
您可能想閱讀Erland Sommarskog的[T-SQL中的動態搜索條件](http://www.sommarskog。se/dyn-search.html) –