此程序运作良好,直到我决定按日期范围获取报告。 表中的CreatedDate列的数据类型为datetime。我将c#中的日期作为文本传递,例如:' 2014-09-31'。这个论点有时也可能是空的。
现在我没有得到任何结果。我也尝试转换为varchar而不是date。我哪里错了。
如果我只是删除了添加的'部分,查询再次正常工作。
ALTER PROCEDURE GetReport
(
@StartDate varchar(10),
@EndDate varchar(10)
)
AS
BEGIN
SET NOCOUNT ON;
IF (@StartDate = '')
SET @StartDate = NULL
IF (@EndDate = '')
SET @EndDate = NULL
DECLARE @query VARCHAR(MAX)
DECLARE @questions VARCHAR(MAX)
SELECT @questions = STUFF((....some code)
SET @query = 'SELECT * FROM
(
SELECT asq.QuestionText, asa.Comments,
ROW_NUMBER() OVER(PARTITION BY asa.FkQuestionId
ORDER BY asa.Comments) Seq
FROM Answers AS asa
LEFT JOIN Questions AS asq ON
asa.FkQuestionId = asq.QuestionId
//---added this part------
WHERE (asa.CreatedDate) >= CONVERT(date,'+@StartDate+')
OR CONVERT(date,'+@StartDate+') IS NULL)
AND (asa.CreatedDate) <= CONVERT(date,'+@EndDate+') OR
CONVERT(date,'+@EndDate+') IS NULL)
//---end------
) AS t
PIVOT
(
MIN(t.Comments)
FOR t.QuestionText IN ('+@questions+')
) AS pvt'
EXECUTE (@query)
END
答案 0 :(得分:1)
如果您的列CreatedDate
是数据类型datetime,那么您需要转换为日期以删除时间部分。时间部分可能不是00:00:00
WHERE ( CAST(asa.CreatedDate AS DATE) >= CONVERT(date,'+@StartDate+')
OR CONVERT(date,'+@StartDate+') IS NULL) )
AND ( CAST(asa.CreatedDate AS DATE) <= CONVERT(date,'+@EndDate+') OR
CONVERT(date,'+@EndDate+') IS NULL) )