I need to concatenate year and month. How could I do that?
select cast(year(orderdate) as int) + ' ' + cast(month(OrderDate)as int) as Year_Month
From sales.SalesOrderHeader
I need to concatenate year and month. How could I do that?
select cast(year(orderdate) as int) + ' ' + cast(month(OrderDate)as int) as Year_Month
From sales.SalesOrderHeader
They were given the option of CONCAT
, but it was implanted in SQL SERVER 2012
, it is very likely that it is using 2008
and is incompatible.
To do concatenation, it must be a string
. As you are doing, an error will occur, so concatenate as follows using YEAR()
and MONTH
with CAST()
:
SELECT CAST(YEAR(orderdate) AS NVARCHAR(4)) + ' ' + CAST(MONTH(orderdate) AS NVARCHAR(2)) AS year_month
Or using DATEPART
:
SELECT CAST(DATEPART(yyyy, orderdate) AS NVARCHAR(4)) + ' ' + CAST(DATEPART(mm, orderdate) AS NVARCHAR(2)) AS year_month
Use the CONCAT function.
SELECT CONCAT(YEAR(OrderDate), '-', MONTH(OrderDate)) AS Year_Month
FROM sales.SalesOrderHeader
In this case, the second parameter of concat is the separator ( '-' ) that defines what will be.
You can use sql's CONCAT
select Concat(cast(year(orderdate) as int), '_' ,cast(month(OrderDate)as int)) as Year_Month From sales.SalesOrderHeader
Returns a string that is the result of concatenating two or more string values. It is available from SQL Server 2005.
Query:
select CONCAT('O ano em que estamos é ', YEAR(GETDATE()),' e o mês é ',
MONTH(GETDATE())) as Data
Note: All arguments are implicitly converted to string types and then concatenated. So it is not necessary to use the% T_ SQL CAST
as you ask.