您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)碛嘘P(guān)SQL中如何判斷給定日期值,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
一、給定一個(gè)日期值,求出此日期所在星期的星期一和星期天的日期數(shù)據(jù)
例如給定一個(gè)日期2010-09-01,求出它所在星期的星期一是2010-08-30,星期天是2010-09-05
Function創(chuàng)建如下:
USE [MSSQL]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[My_OneDay_GetWeekFirstAndEndDay](@tmpDate DATETIME)
RETURNS @tmpTable TABLE(FirstDay DATETIME , EndDay DATETIME)
AS
BEGIN
INSERT INTO @tmpTable
SELECT a.FirstDay,b.EndDay FROM (
SELECT 1 AS ID,DATEADD(wk, DATEDIFF(wk,0,@tmpDate), 0) AS FirstDAy
) a
LEFT JOIN (
SELECT 1 AS ID,DATEADD(wk, DATEDIFF(wk,0,@tmpDate), 6) AS EndDay
) b
ON a.ID = b.ID
RETURN
END
Function測(cè)試:
SELECT * from My_OneDay_GetWeekFirstAndEndDay('2010-09-01')
二、以上面單個(gè)日期搜索為基礎(chǔ),由用戶輸入兩個(gè)參數(shù),一個(gè)是開始日期,一個(gè)結(jié)束日期,根據(jù)這兩個(gè)參數(shù),求出在此時(shí)期段內(nèi)的所有星期的星期一和星期天的日期表并排序。
例如開始日期是2011-09-01,結(jié)束日期是2011-10-06,我們就可以得到此星期表如下:
WeekOrder FirstDay EndDay
1 2011-08-29 00:00:00.000 2011-09-04 00:00:00.000
2 2011-09-05 00:00:00.000 2011-09-11 00:00:00.000
3 2011-09-12 00:00:00.000 2011-09-18 00:00:00.000
4 2011-09-19 00:00:00.000 2011-09-25 00:00:00.000
5 2011-09-26 00:00:00.000 2011-10-02 00:00:00.000
6 2011-10-03 00:00:00.000 2011-10-09 00:00:00.000
Function創(chuàng)建如下:
USE [MSSQL]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[MY_Range_GetWeekFirstAndEndDays](@tmpDateSTART DATETIME,@tmpDateEND DATETIME)
RETURNS @tmpTable TABLE(WeekOrder INT,FirstDay DATETIME , EndDay DATETIME)
AS
BEGIN
DECLARE @tmpDate DATETIME
DECLARE @index INT
SET @tmpDate=@tmpDateSTART
SET @index=1
WHILE @tmpDate <=@tmpDateEND
BEGIN
INSERT INTO @tmpTable
SELECT @index,a.FirstDay,b.EndDay FROM (
SELECT 1 AS ID,DATEADD(wk, DATEDIFF(wk,0,@tmpDate), 0) AS FirstDAy) a
LEFT JOIN (
SELECT 1 AS ID,DATEADD(wk, DATEDIFF(wk,0,@tmpDate), 6) AS EndDay) b
ON a.ID = b.ID
SET @tmpDate=DATEADD(DAY,7,@tmpDate)
SET @index=@index+1
END
RETURN
END
Function測(cè)試:
SELECT * from My_Range_GetWeekFirstAndEndDays('2011-09-01','2011-10-06')
上述就是小編為大家分享的SQL中如何判斷給定日期值了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。