我有一个关于T-SQL的简单问题。我有一个存储过程调用一个返回日期的函数。我想使用IF条件将今天的日期与函数返回日期进行比较。如果返回数据,则为true。
有关处理此问题的最佳方法的任何想法。我现在正在学习t-sql,而且我更熟悉使用C#的逻辑条件。
ALTER FUNCTION [dbo].[monday_new_period](@p_date as datetime) -- Parameter to find current date
RETURNS datetime
BEGIN
-- 1 find the year and period given the current date
-- create parameters to store period and year of given date
declare @p_date_period int, @p_date_period_year int
-- assign the values to the period and year parameters
select
@p_date_period=period,
@p_date_period_year = [year]
from client_week_uk where @p_date between start_dt and end_dt
-- 2 determine the first monday given the period and year, by adding days to the first day of the period
-- this only works on the assumption a period lasts a least one week
-- create parameter to store the first day of the period
declare @p_start_date_for_period_x datetime
select @p_start_date_for_period_x = min(start_dt)
from client_week_uk where period = @p_date_period and [year] = @p_date_period_year
-- create parameter to store result
declare @p_result datetime
-- add x days to the first day to get a monday
select @p_result = dateadd(d,
case datename(dw, @p_start_date_for_period_x)
when 'Monday' then 0
when 'Tuesday' then 6
when 'Wednesday' then 5
when 'Thursday' then 4
when 'Friday' then 3
when 'Saturday' then 2
when 'Sunday' then 1 end,
@p_start_date_for_period_x)
Return @p_result
END
ALTER PROCEDURE [dbo].[usp_data_to_retrieve]
-- Add the parameters for the stored procedure here
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF monday_new_period(dbo.trimdate(getutcdate()) = getutcdate()
BEGIN
-- SQL GOES HERE --
END
谢谢!
答案 0 :(得分:2)
我假设您正在使用Sql2008。有关详细信息,请参阅IF和CASE关键字的文档。
CREATE FUNCTION dbo.GetSomeDate()
RETURNS datetime
AS
BEGIN
RETURN '2012-03-05 13:12:14'
END
GO
IF CAST(GETDATE() AS DATE) = CAST(dbo.GetSomeDate() AS DATE)
BEGIN
PRINT 'The same date'
END
ELSE
BEGIN
PRINT 'Different dates'
END
-- in the select query
SELECT CASE WHEN CAST(GETDATE() AS DATE) = CAST(dbo.GetSomeDate() AS DATE) THEN 1 ELSE 0 END AS IsTheSame
答案 1 :(得分:0)
这是T-SQL IF和日期比较的基本语法。
如果您只是比较日期部分的相等性,则需要使用:
select dateadd(dd,0, datediff(dd,0, getDate()))
此代码段将有效地将时间部分设置为00:00:00,以便您只比较日期。所以在使用中它看起来像这样。
IF dateadd(dd,0, datediff(dd,0, fn_yourFunction())) = dateadd(dd,0, datediff(dd,0, GETDATE()))
BEGIN
RETURN SELECT * FROM SOMEDATA
END
希望有所帮助!