当前位置: 数据库>sqlserver
sql日期范围查询函数fn_ltDate
来源: 互联网 发布时间:2014-08-29
本文导语: 根据日期范围来查询。 表单中输入 2012-05-01 到 2012-10-01, 很容易漏掉 2012-10-01 这一天的记录, 而且总要判断 is null或空串等也比较麻烦,因此实现了这段日期查询函数。 代码示例: IF EXISTS( SELECT * FR...
根据日期范围来查询。
表单中输入 2012-05-01 到 2012-10-01, 很容易漏掉 2012-10-01 这一天的记录, 而且总要判断 is null或空串等也比较麻烦,因此实现了这段日期查询函数。
代码示例:
IF EXISTS(
SELECT *
FROM dbo.sysobjects
WHERE id = OBJECT_ID(N'[dbo].fn_ltDate')
AND (TYPE = 'FN' OR TYPE = 'TF' OR TYPE = 'IF')
)
BEGIN
PRINT '已存在,删除再新建'
DROP FUNCTION fn_ltDate
END
ELSE
BEGIN
PRINT '不存在,新建'
END
GO
--Create by: yenange
--Description: 前日期是否= 0
)
BEGIN
SET @result = 1
END
RETURN @result
END
GO
DECLARE @TempTalbe TABLE (Id INT, CreateTime DATETIME)
INSERT INTO @TempTalbe
SELECT 1,'2012-1-2' UNION
SELECT 2,'2012-3-2 00:00:00' UNION
SELECT 3,'2012-4-2' UNION
SELECT 4,'2012-5-2 23:59:59' UNION
SELECT 5,'2012-6-2 23:59:59'
--参数为 datetime 型
DECLARE @StartDate1 DATETIME
DECLARE @EndDate1 DATETIME
SET @StartDate1 = '2012-3-2'
SET @EndDate1 = ''
SELECT *
FROM @TempTalbe t
WHERE dbo.fn_ltDate(@StartDate1, CreateTime) = 1
AND dbo.fn_ltDate(CreateTime, @EndDate1) = 1
--参数为 varchar 型
DECLARE @StartDate2 VARCHAR(10)
DECLARE @EndDate2 VARCHAR(10)
SET @StartDate1 = '2012-3-2'
SET @EndDate1 = '2012-5-2'
SELECT *
FROM @TempTalbe t
WHERE dbo.fn_ltDate(@StartDate1, CreateTime) = 1
AND dbo.fn_ltDate(CreateTime, @EndDate1) = 1
SELECT *
FROM dbo.sysobjects
WHERE id = OBJECT_ID(N'[dbo].fn_ltDate')
AND (TYPE = 'FN' OR TYPE = 'TF' OR TYPE = 'IF')
)
BEGIN
PRINT '已存在,删除再新建'
DROP FUNCTION fn_ltDate
END
ELSE
BEGIN
PRINT '不存在,新建'
END
GO
--Create by: yenange
--Description: 前日期是否= 0
)
BEGIN
SET @result = 1
END
RETURN @result
END
GO
DECLARE @TempTalbe TABLE (Id INT, CreateTime DATETIME)
INSERT INTO @TempTalbe
SELECT 1,'2012-1-2' UNION
SELECT 2,'2012-3-2 00:00:00' UNION
SELECT 3,'2012-4-2' UNION
SELECT 4,'2012-5-2 23:59:59' UNION
SELECT 5,'2012-6-2 23:59:59'
--参数为 datetime 型
DECLARE @StartDate1 DATETIME
DECLARE @EndDate1 DATETIME
SET @StartDate1 = '2012-3-2'
SET @EndDate1 = ''
SELECT *
FROM @TempTalbe t
WHERE dbo.fn_ltDate(@StartDate1, CreateTime) = 1
AND dbo.fn_ltDate(CreateTime, @EndDate1) = 1
--参数为 varchar 型
DECLARE @StartDate2 VARCHAR(10)
DECLARE @EndDate2 VARCHAR(10)
SET @StartDate1 = '2012-3-2'
SET @EndDate1 = '2012-5-2'
SELECT *
FROM @TempTalbe t
WHERE dbo.fn_ltDate(@StartDate1, CreateTime) = 1
AND dbo.fn_ltDate(CreateTime, @EndDate1) = 1
SQL时间段查询实例分享
SQL递归查询实例
sql语句之递归查询
sql server模糊查询语句示例
sql server 模糊查询的常用方法举例
sql递归查询代码(cte应用)
sql2005递归查询的例子
sql 递归查询的代码(图文)