我的表格有一個列date_period,其格式爲YYYYMM。我想寫一個查詢,在date_period列中插入日期,格式爲YYYYMM如果當前月份沒有條目。我如何從表格中存儲的兩個日期中獲得月份差異,格式爲YYYYMM
例如:日期有效期至2015年10月,因此它將包含值。現在我想檢查並插入數據直到當前月份,如果它不存在。所以參賽作品現在是201511,201512,201601
我該如何做到這一點?
我的表格有一個列date_period,其格式爲YYYYMM。我想寫一個查詢,在date_period列中插入日期,格式爲YYYYMM如果當前月份沒有條目。我如何從表格中存儲的兩個日期中獲得月份差異,格式爲YYYYMM
例如:日期有效期至2015年10月,因此它將包含值。現在我想檢查並插入數據直到當前月份,如果它不存在。所以參賽作品現在是201511,201512,201601
我該如何做到這一點?
嘗試這種方式,可能它會幫助你
DECLARE @v DATE= getdate()
declare @Currentdate varchar(10)
set @Currentdate=CONVERT(VARCHAR(10), @v, 112)
/*@Currentdate string is in format '20160129'*/
IF NOT EXISTS(select * from Table1 where date_period=LEFT(@Currentdate,6))
begin
insert into Table1(date_period)values(LEFT(@Currentdate,6))
end
我認爲這將是你的問題的完整解決方案
declare @monthcount int
DECLARE @v DATE= getdate()
declare @lastsavedMonth varchar(20)= (select MAX(date_period) from Table1)
declare @Lastsaveddate varchar(20)= @lastsavedMonth+''+RIGHT(CONVERT(VARCHAR, 100 + DATEPART(d,@v)), 2)
set @monthcount=datediff(month,@Lastsaveddate,CONVERT(VARCHAR(10), @v, 112))
while @monthcount>=0
begin
declare @dateofsavingmonth varchar(20)
if(@monthcount=0)
begin
set @dateofsavingmonth=CONVERT(VARCHAR(10),@v,112)
end
else
begin
set @dateofsavingmonth=CONVERT(VARCHAR(10), dateadd(month,[email protected],@v),112)
end
IF NOT EXISTS(select * from Table1 where date_period=LEFT(@dateofsavingmonth,6))
begin
insert into Table1(date_period)values(LEFT(@dateofsavingmonth,6))
end
set @monthcount [email protected]
end
我已經這樣做了,就好像當前月份日期不存在那麼它會將該日期添加到date_period列。但我的問題是如何檢測到當前月份有多少月沒有插入。在上面的例子中,我只插入日期到十月份,現在我想插入剩餘的月份日期,直到當前月份。 –
非常感謝!它工作得很好:) –
你能解釋一下這行: declare @Lastsaveddate varchar(20)= @lastsavedMonth +''+ RIGHT(CONVERT(VARCHAR,100 + DATEPART(d,@ v)),2) –
它們轉換成日期使用Convert();然後按月執行DateDiff。 –
@munmun什麼是你採取的數據類型date_period列? – Meer
@MeerDeen其** int **數據類型 –