使用:SQL Server 2008 R2
我想编写一个查询,它将以日期时间格式每天选择(按单列排序)。
实施例
2012-02-02 00:00:00
2012-02-02 00:00:01
2012-02-02 00:00:02
2012-02-02 00:00:03
2012-02-02 00:00:04
...
2012-02-02 23:59:58
2012-02-02 23:59:59
是的,认真的。
如果需要,我可以创建一个数字表,如果我可以将整数值转换为日期时间,这可能会有所帮助。
提前致谢。
答案 0 :(得分:6)
这假设一个数字表的值最高为86,400 ...一天中的秒数。
为了说明,我在这里创建一个数字表......但你应该提前做到这一点。
SET NOCOUNT ON
DECLARE @YourDate DATETIME
SET @YourDate = '2/2/2012'
DECLARE @Numbers TABLE (Number INT)
DECLARE @Index INT
SET @Index = 0
WHILE (@Index < 86400)
BEGIN
INSERT INTO @Numbers VALUES (@Index)
SET @Index = @Index + 1
END
SELECT DATEADD(SECOND, n.Number, @YourDate)
FROM @Numbers n
WHERE n.Number < 86400
答案 1 :(得分:3)
如果您不想依赖表或递归CTE,请使用一些交叉连接。如果你的序列需要更多的数字,只需添加更多的交叉连接 - 你可以很快地超过几百万。
DECLARE @start_date AS DATETIME = '2012-02-02';
WITH L0 AS (SELECT 1 AS C UNION ALL SELECT 1), -- 2
L1 AS (SELECT L0.C FROM L0 CROSS JOIN L0 AS B), -- 4
L2 AS (SELECT L1.C FROM L1 CROSS JOIN L1 AS B), -- 16
L3 AS (SELECT L2.C FROM L2 CROSS JOIN L2 AS B), -- 256
L4 AS (SELECT L3.C FROM L3 CROSS JOIN L3 AS B), -- 65536
L5 AS (SELECT L4.C FROM L4 CROSS JOIN L4 AS B), -- Alot
N AS (SELECT ROW_NUMBER() OVER(ORDER BY L5.C) AS n FROM L5),
D AS (SELECT DATEADD(SECOND, n - 1, @start_date) AS d, n FROM N)
SELECT d from D where n <= (60 * 60 * 24)
答案 2 :(得分:2)
如果您不想依赖另一个表,使用CTE
,而可能更多的CPU密集可能是另一种选择。
;WITH q (TimeOfDay) AS (
SELECT DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
UNION ALL
SELECT DATEADD(ss, 1, q.TimeOfDay)
FROM q
WHERE DAY(GETDATE()) = DAY(DATEADD(ss, 1, q.TimeOfDay))
)
SELECT *
FROM q
OPTION (MAXRECURSION 0)