How to perform SQL concatenation

3

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
    
asked by anonymous 14.08.2017 / 18:15

4 answers

2

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
    
14.08.2017 / 18:40
1

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.     

14.08.2017 / 18:23
1

You can use sql's CONCAT

link

select Concat(cast(year(orderdate) as int),  '_'  ,cast(month(OrderDate)as int)) as Year_Month From sales.SalesOrderHeader
    
14.08.2017 / 18:24
1

CONCAT (Transact-SQL)

  

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.

SQLFiddle

    
14.08.2017 / 18:43