简体   繁体   English

在SQL Server 2008和2012中并置

[英]Concatenating in SQL Server 2008 and 2012

I have this concatenating function that works fine in SQL Server 2012: 我具有在SQL Server 2012中正常运行的此串联函数:

declare @reportN nvarchar(255)
set @reportName = concat(year(getdate()), '-',33);

select @reportN

Which gives result 2013-33 得出2013-33年的结果

I also have SQL Server 2008 which doesn't support concat function so when I try to do it following way. 我也有不支持concat函数的SQL Server 2008,因此当我尝试按以下方式进行操作时。

declare @r nvarchar(255)
set @r = (year(getdate()) + '-' + 33);
select @r

I get result of 2046 basically it adds it. 我基本上得到2046的结果,它将它添加。 Can you let me know how to fix it so I get it result of 2013-33. 您能否让我知道如何解决它,以便获得2013-33年的结果。 Thanks 谢谢

You can just cast the year as a string: 您可以将年份强制转换为字符串:

  declare @r nvarchar(255)
  set @r= CAST(YEAR(GETDATE()) AS CHAR(4)) +'-33';
  select @r

The CONCAT() function in 2012 converts all inputs to strings, you need to explicitly do this prior to 2012 if you want to concatenate strings. 2012年的CONCAT()函数将所有输入都转换为字符串,如果要串联字符串,则需要在2012年前显式地执行此操作。

You need to make your year(getDate()) a CHAR (or some other text). 您需要将year(getDate())设为CHAR(或其他文字)。 You are concatenating it to an integer 33. Since year() returns an INT and you are concatenating to an INT (33) it returns and INT. 您将其连接为整数33。由于year()返回INT,并且您将连接为INT(33),因此返回并返回INT。

declare @r nvarchar(255)
set @r=(CONVERT(CHAR(4), year(getdate()))+'-'+'33');
select @r

Convert 33 to varchar: 将33转换为varchar:

declare @r nvarchar(255)
      set @r=(convert(varchar(4),year(getdate()))+'-'+'33');
      select @r

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM