對於SQL Server 2012(感謝漂泊和i-一個)
DECLARE @now DATETIME = CURRENT_TIMESTAMP;
SELECT DATEADD(DAY, 1, EOMONTH(@now, -1));
-- or
SELECT DATEFROMPARTS(YEAR(@now), MONTH(@now), 1);
對於SQL Server 2008+
DECLARE @now DATETIME = CURRENT_TIMESTAMP;
-- This shorthand works:
SELECT CONVERT(DATE, @now+1-DAY(@now));
-- But I prefer to be more explicit, instead of relying on
-- shorthand date math (which doesn't work in all scenarios):
SELECT CONVERT(DATE, DATEADD(DAY, 1-DAY(@now), @now));
對於SQL Server 2005
SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()),0);
如果您使用的是SQL Server 2005方法,則需要注意:在查詢中使用涉及DATEDIFF
的表達式時需要注意。 SQL Server can transpose the arguments and lead to horrible estimates - as seen here。採取效率稍低的字符串方法可能更安全一些:
SELECT CONVERT(DATETIME, CONVERT(CHAR(6), GETDATE(), 112) + '01');
謝謝馬克用正確的方式編輯它。 :) – TanmoyDB
什麼版本的SQL Server?另外你會使用這個? –
@AaronBertrand:正在使用SS-2008R2 – TanmoyDB