我正在尝试创建一个验证年度日期的程序。日期在BD中存储一次,但在我的winform日历中每年显示一次(我在C#中每年使用粗体日期)。所以我想对查询做的是检查月份和日期就像存储在表格中的日期,但不起作用。这是我的问题:
SELECT IdCalendar,
Description,
DateCalendar,
Annualy
FROM Calendar
WHERE
(DATEPART(MONTH,DateCalendar) like DATEPART(MONTH,@DateCalendar)) AND
(DATEPART(DAY,DateCalendar) like DATEPART(DAY,@DateCalendar))
例如,我存储的DateCalendar是' 2015-12-04',我的参数@DateCalendar是' 2016-12-04'。关于如何做更好的查询的任何想法?
修改
查询没有任何错误或警告。只返回0行。我的DateCalendar存储为DateTime。
SP:
CREATE PROC [dbo].[usp_app_Calendar_Search]
@DateCalendar DATETIME,
@Result SMALLINT OUTPUT,
@Message VARCHAR(1000) OUTPUT
AS
BEGIN
DECLARE @vResult SMALLINT, @vMessage VARCHAR(1000)
SELECT @vResult = 0, @vMessage = ''
BEGIN TRY
IF EXISTS (SELECT * FROM Calendar WHERE DateCalendar = @DateCalendar)
BEGIN
IF(@DateCalendar = 0) SET @DateCalendar = NULL
SELECT IdCalendar,
Description,
DateCalendar,
Annualy
FROM Calendar
WHERE
(DATEPART(MONTH,DateCalendar) like DATEPART(MONTH,@DateCalendar)) AND
(DATEPART(DAY,DateCalendar) like DATEPART(DAY,@DateCalendar))
SET @vResult = 1
SET @vMessage = 'Done'
END
ELSE BEGIN
SET @vResult = 0
SET @vMessage = 'Error.'
END
END TRY
BEGIN CATCH
SET @vResult = -1
SET @vMessage = 'Error: ' + ERROR_MESSAGE() + ' Line: ' + CAST(ERROR_LINE() AS VARCHAR)
END CATCH
SELECT @Result = @vResult, @Message = @vMessage
END
提前致谢。
答案 0 :(得分:1)
问题在于fetchApplianceRealtime
。我重写你的SP:
IF EXISTS (SELECT * FROM Calendar WHERE DateCalendar = @DateCalendar)
修改强>
现在CREATE PROC [dbo].[usp_app_Calendar_Search]
@DateCalendar DATETIME,
@Result SMALLINT OUTPUT,
@Message VARCHAR(1000) OUTPUT
AS
BEGIN
DECLARE @vResult SMALLINT = 0
,@vMessage VARCHAR(1000) = '';
IF(@DateCalendar = 0) SET @DateCalendar = NULL;
BEGIN TRY
SELECT IdCalendar,
Description,
DateCalendar,
Annualy
FROM Calendar
WHERE DATEPART(MONTH,DateCalendar) = DATEPART(MONTH,@DateCalendar)
AND DATEPART(DAY,DateCalendar) = DATEPART(DAY,@DateCalendar);
IF @@ROWCOUNT > 0
SELECT @vResult = 1, @vMessage = 'Done'
ELSE
SELECT @vResult = 0, @vMessage = 'Error.';
END TRY
BEGIN CATCH
SET @vResult = -1
SET @vMessage = 'Error: ' + ERROR_MESSAGE() + ' Line: '
+ CAST(ERROR_LINE() AS VARCHAR)
END CATCH
SELECT @Result = @vResult, @Message = @vMessage;
END
条件不是SARGable,这意味着查询优化器将跳过WHERE
列上的索引(如果存在的话)。
您可以使用评论中建议的@Tom Page等计算列:
DateCalendar