@begin_date = '2007-08-28';
@end_date = '2013-06-07'
if ( @end_date IS NULL OR @end_date = '' )
begin
set @my_return = DATEDIFF( MM, @begin_date, GETDATE() ) % 12
end
else
begin
set @my_return = DATEDIFF( MM, @begin_date, @end_date ) % 12
end
Tag : .NET, Ms SQL Server 2005, Ms SQL Server 2008, Ms SQL Server 2012, Ms SQL Server 2014, Ms SQL Server 2016
Date :
2017-06-09 12:52:38
By :
txais
View :
2261
Reply :
8
No. 1
Guest
Code (SQL)
IF OBJECT_ID('tempdb..#Fuck') IS NOT NULL DROP TABLE #Fuck;
DECLARE @month TINYINT = MONTH(GETDATE()); -- เดือนปัจจูบัน
DECLARE @Cols NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX)
;WITH CTE_Days AS
(
SELECT DATEADD(month, @month, DATEADD(month, -MONTH(GETDATE()), DATEADD(day, -DAY(GETDATE()) + 1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME)))) D, 1 AS RN, 0.0 AS Amt
UNION ALL
SELECT DATEADD(day, 1, D), RN + 1, 0.0
FROM CTE_Days
WHERE D < DATEADD(day, -1, DATEADD(month, 1, DATEADD(month, @month, DATEADD(month, -MONTH(GETDATE()), DATEADD(day, -DAY(GETDATE()) + 1, CAST(FLOOR(CAST(GETDATE() AS FLOAT)) AS DATETIME))))))
)
SELECT * INTO #Fuck FROM CTE_Days
select @Cols = STUFF((SELECT (',' + QuoteName(RN))
FROM #Fuck Mom
GROUP BY Mom.RN
ORDER BY Mom.RN ASC --Fixed 1, 10, 11, 12, ...
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @query = 'SELECT RN,' + @cols + ' from
(
select RN, DAY(D) AS D, Amt
from #Fuck ' + '
) src
pivot
(
sum(Amt)
for [D] in (' + @cols + ')
) piv '
EXECUTE(@query);
IF OBJECT_ID('tempdb..#Fuck') IS NOT NULL DROP TABLE #Fuck;
Code ครับ
@begin_date = '2007-08-28';
@end_date = '2013-06-07'
if ( @end_date IS NULL OR @end_date = '' )
begin
set @my_return = DATEDIFF( MM, @begin_date, GETDATE() ) % 12
end
else
begin
set @my_return = DATEDIFF( MM, @begin_date, @end_date ) % 12
end
ยกตัวอย่าง 2.
Quote:
DECLARE @begin_date date = '2007-08-28';
DECLARE @end_date date = '2013-06-07'
DECLARE @my_return int;
if ( @end_date IS NULL OR @end_date = '' )
begin
set @my_return = DATEDIFF( MM, @begin_date, GETDATE() ) % 12
end
else
begin
set @my_return = DATEDIFF( MM, @begin_date, @end_date ) %12
end
SELECT @my_return