在我的项目,我创建静态类DataManager
暴露所需的所有功能,获得数据,例如
public static IList<ActionHistoryData> GetActionHistoryList(DateTime startDate, DateTime endDate, bool postprocessed)
{
return GlobalComponents.DataManagerImpl.GetActionHistoryList(null, null, null, null, null, null, null, startDate, endDate, false, postprocessed, null);
}
public static ActionHistoryData GetActionHistory(int id)
{
IList<ActionHistoryData> actionHistoryList =
GlobalComponents.DataManagerImpl.GetActionHistoryList(id, null, null, null, null, null, null, null, null, null, null, null);
CQGUtils.Verify(!CollectionsUtil.IsEmpty(actionHistoryList), "There is no action history with [ID='{0}']", id);
CQGUtils.Verify(actionHistoryList.Count == 1, "More than one action history returned.");
return actionHistoryList[0];
}
正如你在DB看到我们只有一个存储过程GetActionHistoryList
(用于ActionHistory
表数据),它有许多不同的参数。 存储过程包含动态SQL例如
`<select statement part>`
DECLARE @where nvarchar(4000);
SET @where = N' WHERE '
IF @ID IS NOT NULL
SET @where = @where + '(ah.ID = @ID) AND '
IF @AccountID IS NOT NULL
SET @where = @where + '(ah.AccountID = @AccountID) AND '
IF @SourceKind IS NOT NULL
SET @where = @where + '(ah.SourceKind = @SourceKind) AND '
IF @SourceIDArray IS NOT NULL
SET @where = @where + '(ah.SourceID IN ('+ @SourceIDArray +')
IF @Postprocessed IS NOT NULL
SET @where = @where + '(ah.Postprocessed = @Postprocessed) AND '
IF @StartDate IS NOT NULL
SET @where = @where + '(ah.UtcTimestamp >= @StartDate) AND '
IF @EndDate IS NOT NULL
SET @where = @where + '(ah.UtcTimestamp <= @EndDate) AND '
) AND '
SET @where = @where + ' 1=1'
SET @query = @[email protected]+' order by utcTimestamp desc '
EXEC sp_executesql @query,
N'
@ID int,
@AccountID int,
@SourceKind tinyint,
@SourceIDArray nvarchar(max),
@NotificationID int,
@DataRequestID int,
@NotificationName nvarchar(250),
@StartDate datetime,
@EndDate datetime,
@MostRecent bit,
@Postprocessed bit,
@TopLimit int
',
@ID = @ID,
@AccountID = @AccountID,
@SourceKind = @SourceKind,
@SourceIDArray = @SourceIDArray,
@NotificationID = @NotificationID,
@DataRequestID = @DataRequestID,
@NotificationName = @NotificationName,
@StartDate = @StartDate,
@EndDate = @EndDate,
@MostRecent = @MostRecent,
@Postprocessed = @Postprocessed,
@TopLimit = @TopLimit
这种方法允许方便地添加新的筛选要求
感谢Stas - 在我看来,你已经采用了将所有20个参数(或者说很多参数)传递给调用存储过程的代码的方法,对每个不需要的参数都使用null参数。这与我在顶级代码中动态构建sql的方式大致相似。但是,我试图通过传递一个选择参数来实现这一点。 – David 2011-03-27 20:33:11