SQL查询:如何获取月份和年份列的日期引用?

时间:2016-07-06 06:42:58

标签: sql sql-server sql-server-2008

我需要帮助来改变月份和月份。年份列为结果中的日期。

前:

表名:AA

Month Year
4     2016
5     2015

结果应该是:

01-04-2016
01-05-2015

我需要一个SQL查询吗?任何人都可以帮助我吗?

8 个答案:

答案 0 :(得分:1)

试试这个,

DECLARE @AA TABLE (
    Month INT
    ,Year INT
    )

INSERT INTO @AA (
    Month
    ,Year
    )
VALUES (
    4
    ,2016
    )
    ,(
    5
    ,2015
    )

SELECT convert(DATE, convert(VARCHAR(50), year * 10000 + month * 100 + 01)) AS DATE
FROM @AA

答案 1 :(得分:0)

试试这段代码:

select '01-'+cast([month] as nvarchar) + '-'+cast([Year] as nvarchar)
from YourTable

答案 2 :(得分:0)

假设int数据类型:

DECLARE @Month int = 4, @Year int = 2016

SELECT CAST(CAST(@Year * 10000 + @Month * 100 + 01 As char(8)) as date)

假设char / varchar数据类型:

DECLARE @MonthString varchar(2) = 4, @YearString char(4) = 2016

SELECT CAST(@YearString +'-'+ RIGHT('00' + @MonthString, 2) + '-01' as date)

两种情况都有结果:

2016-04-01 -- (Date data type)

答案 3 :(得分:0)

为保留关键字添加方括号:

DECLARE @AA TABLE ([Month] INT, [Year] INT);

INSERT INTO @AA ([Month], [Year]) VALUES 
(4, 2016),
(5, 2015);

SELECT '01-' + RIGHT('00' + CAST([MONTH] AS VARCHAR), 2) + '-' + CAST([Year] AS VARCHAR)  
FROM @AA

结果:

01-04-2016
01-05-2015

答案 4 :(得分:0)

DECLARE @Table1 TABLE 
    (Month int, Year int)
;

INSERT INTO @Table1
    (Month, Year)
VALUES
    (4, 2016),
    (5, 2015)
;

select '01'+'-'+RIGHT('000'+CAST(Month AS VARCHAR(3)),2)+'-'+CAST(Year AS VARCHAR) from @Table1

答案 5 :(得分:0)

不要进行varchar转换。使用如下

declare @t table([Month] int,[Year] int)
insert into @t 
select 4,     2016 union all
select 5,     2015

select dateadd(month,month-1,dateadd(year,[year]-1900,0)) from @t

答案 6 :(得分:0)

您可以使用concat函数来解决此问题

SESSION

答案 7 :(得分:0)

试试这个:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String name=request.getParameter("uname");
    PrintWriter out=response.getWriter();
    out.println("welcome "+name);
    out.println("<a href='SentItems?uname="+name+" '>sent items</a>");
    out.println("<a href=''>Logout</a>");
}