在SQL函数(UDF)中查找指定月份的第一天(01)和最后一天(28),作为示例(20091207)? [英] Find the first Day (01) and the Last Day (28) for a specified month in SQL Function (UDF), as an example (20091207)?
问题描述
当我指定日期时,我需要编写一个SQL函数(UDF)来查找第一天(int)和最后一天(int)。
例如:当我指定(20130217)(即2013年2月17日)时,我应该能够找到第一天(01)和最后一天(28)指定的月份(在这种情况下,2月)。
我该怎么做?请提供必要的代码以在我的SQL函数中实现此功能。
谢谢。
I need to write an SQL Function (UDF) to find the First Day (int) and the Last Day (int) when I specify a date.
For example: When I specify (20130217) (i.e. Feb 17th, 2013), I should be able to find the First Day (01) and the Last Day (28) for the specified month (in this case, Feb).
How can I do that? Please provide the necessary code to implement this feature in my SQL Function.
Thanks.
推荐答案
第一天总是1,所以有50%的工作完成了!
至于最后一天,你可以试试
The first day is always 1 so there''s 50% of your work done!
As for the last day, you could try
CREATE FUNCTION dbo.LastDayInMonth (@when DATETIME)
RETURNS Int
AS
BEGIN
Declare @lastDate int
SELECT @lastdate = DAY(DATEADD(DAY,-1,DATEADD(MONTH,1,DATEADD(DAY,1-DAY(@when),@when))))
RETURN @lastDate
End
我用Google搜索以省去麻烦
which I googled for to save you the trouble
试试这样...
Hi ,
Try like this...
DECLARE @Date VARCHAR(10)='20120404', @FirstDate VARCHAR(10), @FirstDay INT, @LastDay INT
SELECT @FirstDate=SUBSTRING(@Date,1,6)+'01'
SELECT @FirstDay=1, @LastDay=DATEDIFF(DAY,@FirstDate,DATEADD(MONTH,1,CONVERT(DATETIME,@FirstDate,103)))
SELECT RIGHT('00'+CAST(@FirstDay AS VARCHAR(5)),2) 'FirstDay', RIGHT('00'+CAST(@LastDay AS VARCHAR(5)),2) 'LastDay'
问候,
GVPrabu
Regards,
GVPrabu
你甚至可以在一行中完成
you can even do it in one line
SELECT DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
SELECT DATEADD(DAY, -(DAY(DATEADD(MONTH, 1, GETDATE()))),DATEADD(MONTH, 1, GETDATE()))
这篇关于在SQL函数(UDF)中查找指定月份的第一天(01)和最后一天(28),作为示例(20091207)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!