我正在使用SQL Server 2008。
我得到了一个包含这5列的表格:
StartMonth, StartYear, EndMonth, EndYear, DaysBetween
我没有这些日期的那一天,而这正是我想要产生的。
例如:
12 2008 1 2009 8
我想创建随机日期(开始日期和结束日期,格式为dd / mm / yyyy),其中包含日,并会在我在天之间的数据
例如,如果我知道我有8天(DaysBetween
)且startmonth
为12,则日期必须
从2008年12月24日起,如果我加8天,我得到EndMonth
(1/2009)
如果我选择日期2/12/2008,我会得到10/12/2008,这不是很好,因为月份仍然是12 ....我需要1(2009)
如何生成有效日期?
答案 0 :(得分:0)
你需要部分来解决这个问题:
DaysBetween
要创建随机值,请尝试以下方法:
SELECT Cast(( DAYSBETWEEN ) * Rand(Cast(Newid() AS VARBINARY)) + 1
AS
TINYINT) AS 'randomNumber'
FROM TABLE
然后添加dateadd函数:
SELECT Dateadd(DD, Cast(( DAYSBETWEEN ) * Rand(Cast(Newid() AS
VARBINARY))
+ 1 AS
TINYINT), Dateadd(MONTH, 1,
Cast(
Cast(STARTMONT AS VARCHAR(2)) + '-01-'
+ Cast(@StartYear AS VARCHAR(4)) AS DATE)))
FROM TABLE
答案 1 :(得分:0)
这样的东西?
WITH N(n) AS (
SELECT a*6+b FROM
(VALUES(0),(1),(2),(3),(4),(5))a(a),
(VALUES(1),(2),(3),(4),(5),(6))b(b)
), T(StartMonth,StartYear,EndMonth,EndYear,DaysBetween) AS (
SELECT 12, 2008, 1, 2009, 8
)
SELECT *
FROM (
SELECT *, DATEADD (dd, -n, DATEADD (mm, StartMonth, DATEADD (yy, StartYear - 1900, '19000101'))) AS dt
FROM T
INNER JOIN N ON DaysBetween >= n
) T
WHERE MONTH (dt) = StartMonth
AND YEAR (dt) = StartYear
AND MONTH (DATEADD (dd, DaysBetween, dt)) = EndMonth
AND YEAR (DATEADD (dd, DaysBetween, dt)) = EndYear
答案 2 :(得分:0)
以下是一个示例:
WITH CTE_Start AS
(
SELECT DATEADD(dd,-(ABS(CHECKSUM(NewId())) % DaysBetween+1),dateadd(mm, (EndYear - 1900) * 12 + EndMonth - 1,0)) StartDate, DaysBetween
FROM dbo.This5Columns
)
SELECT StartDate, DATEADD(dd,DaysBetween,StartDate) AS EndDate
FROM CTE_Start
ABS(CHECKSUM(NewId())) % DaysBetween+1
用于获取1到DaysBetween,
dateadd(mm, (EndYear - 1900) * 12 + EndMonth - 1,0)
获取结束月份的第一个日期(最早可能的结束日期)
然后你减去两个来获取你的StartDate,再次添加DaysBetween以获得EndDate
<强> SQLFiddle DEMO 强>