对于 SQL Server 2012(感谢 adrift 和 i-one)
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 可以转置参数并导致可怕的估计-如此处所示。采用效率稍低的字符串方法实际上可能更安全:
SELECT CONVERT(DATETIME, CONVERT(CHAR(6), GETDATE(), 112) + '01');