我需要在输入时获取前一个月和一年。所以如果用户输入 201412 那么它应该返回 201411。如果他们输入 201501 那么它应该返回 201401。
A quick way to do this on a SQL Server database would be to create a date element out of your string, convert it to a date type, then use the function dateadd and add -1 month (subtract one month if you like)
Like this:
select DATEADD(MONTH,-1,CAST(LEFT(201401,4)+'-'+RIGHT(201401,2)+'-01' AS DATE))
The steps broken down:
In SQL Server
DECLARE @dateAsNumber VARCHAR(8);
SET @dateAsNumber = '198705';
DECLARE @DateConvertedFromNumber DATETIME;
SELECT @DateConvertedFromNumber = CONVERT (DATETIME, CONVERT(CHAR(8), @dateAsNumber
+ '01'))
SELECT LEFT(CONVERT(VARCHAR, DATEADD(YEAR, -1,
@DateConvertedFromNumber), 112),
6) AS 'Year Before'
SELECT LEFT(CONVERT(VARCHAR, DATEADD(MONTH, -1,
@DateConvertedFromNumber), 112),
6) AS 'Month Before'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.