如何在括号中设置投射值?

时间:2015-03-17 06:34:59

标签: sql casting

我正在尝试投两个数据。我想把演员数据放在一个括号内。我试过这样的:

SELECT EmpCode,
       (CAST(Name AS varchar(50))+' '+CAST(EmpCode AS varchar(50))) AS Name
from ShiftAllocation  

它为Name和EmpCode提供输出,如

  

Tom Varghees 12345

但我想把这个12345(EmpCode)放在一个括号中。 预期输出

  

Tom Varghees [12345]

我在示例查询中应该做些什么更改

2 个答案:

答案 0 :(得分:2)

您可以使用QUOTENAME

SELECT EmpCode, 
       (CAST(Name AS VARCHAR(50)) + ' ' + 
       QUOTENAME(CAST(EmpCode AS VARCHAR(50)))) AS Name 
FROM   ShiftAllocation  

如果您无法使用QUOTENAME,则可以进入以下网址:

SELECT EmpCode, 
       (CAST(Name AS VARCHAR(50)) + 
       ' [' + CAST(EmpCode AS VARCHAR(50)) + ']') AS Name 
FROM   ShiftAllocation  

答案 1 :(得分:1)

简单地添加括号,不需要火箭科学:

SELECT 'Peter'+' ['+ '12345'+']' AS Name 

在您的查询中:

SELECT EmpCode,(CAST(Name AS varchar(50))+' ['+CAST(EmpCode AS varchar(50)) +']') AS Name from ShiftAllocation