我需要根据给定的输入参数编写一个使用不同where子句的存储过程。具体来说,我需要评估两个日期时间参数,并根据这些参数,我需要构造不同的where子句。到目前为止,我在使其工作时遇到了问题。
存储过程采用用户给出的开始日期和结束日期参数,并使用这两个参数查找开始日期和结束日期与这些用户输入参数重叠的记录。
下面是我要创建的存储过程的伪代码:
CREATE PROCEDURE sp_MyReport @organisation nvarchar(255) = NULL, @start_date nvarchar(255) = NULL, @end_date nvarchar(255) = NULL
AS
DECLARE @dateTimeOverlapWhereClause nvarchar(1000)
-- Construct the appropriate where-condition based on the user input
if @start_date is not null and @end_date is not null
@dateTimeOverlapWhereClause = (cast(start_date as datetime) <= prj.PlanEnd) and (cast(end_date as datetime) >= prj.PlanStart)
else if @start_date is not null and @end_date is null
@dateTimeOverlapWhereClause = (prj.PlanStart >= cast(@start_date as datetime))
else if @start_date is null and @end_date is not null
@dateTimeOverlapWhereClause = (prj.PlanEnd <= cast(@end_date as datetime))
else -- both input dates are null so we use open-ended dates instead
@dateTimeOverlapWhereClause = ((cast('1900-01-01' as datetime) <= prj.PlanEnd) and (cast('9999-12-31' as datetime) >= prj.PlanStart))
-- This is the query that need to use the dynamic where condition
select
prj.SrcGISID,
prj.PlanStart,
prj.PlanEnd,
prj.WorksClass,
prj.Description,
prj.JobStatus,
prj.Stage
from PROJECT prj
inner join ORGANISATION org on prj.OrgID = org.ID and org.OrganisationName = @organisation
and @dateTimeOverlapWhereClause
go
如何动态构建@dateTimeOverlapWhereClause?我做了一些研究,但大多数答案都是基于简单的变量。 SQL注入在这里并不是一个问题,因为这个存储过程是由组织内部使用的。我正在使用MS SQL Server 2012。
提前致谢。