Convert Text to int but output as text

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • aball01234
    New Member
    • Dec 2012
    • 1

    Convert Text to int but output as text

    I want add a number to a text value and have it appear in
    output. Original value column Extension is a text that I
    want to add 2100, but I want to have it output to a text.

    Using Northwind database, table Employees:

    Code:
    Select 
      (E.EmployeeID) as 'EmployeeID_ab',
      (E.Extension)  as 'Extension_ab' 
    From Employees E
    Returns rows like this:
    Code:
    EmployeeID_ab  Extension_ab
         1           5467
         2           3457
    I want rows like this after adding 2100:
    Code:
    EmployeeID_ab  Extension_ab
         1           7567
         2           5557
    Last edited by NeoPa; Dec 14 '12, 08:01 PM. Reason: Added mandatory [CODE] tags.
  • NeoPa
    Recognized Expert Moderator MVP
    • Oct 2006
    • 32661

    #2
    I doubt that's true. The syntax for the SQL appears wrong to me in that the ALIAS commands (abbreviated to as in your case) use string literals instead of valid names.

    You're probably looking for :
    Code:
    SELECT CAST(E.EmployeeID AS int) + 2100 AS [EmployeeID_ab]
         , CAST(E.Extension AS int) + 2100 AS [Extension_ab]
    FROM   Employees AS E

    Comment

    • Rabbit
      Recognized Expert MVP
      • Jan 2007
      • 12517

      #3
      In SQL Server, it is valid to put the alias in quotes.

      If you want the final result to be a text data type, take what NeoPa did and put another cast around the expression and cast it back to text.

      Comment

      • NeoPa
        Recognized Expert Moderator MVP
        • Oct 2006
        • 32661

        #4
        Originally posted by Rabbit
        Rabbit:
        In SQL Server, it is valid to put the alias in quotes.
        My bad. Rabbit is far more experienced than I am in SQL Server as I no longer have one to work on even, so if he says I'm wrong, then the chances are pretty high that I am.

        He is also correct that I overlooked your clear request to convert it back to Text afterwards. I was only thinking of it displaying on the screen, but that wasn't the question. So :
        Code:
        SELECT CAST(CAST(E.EmployeeID AS int) + 2100, AS nvarchar) AS [EmployeeID_ab]
             , CAST(CAST(E.Extension AS int) + 2100, AS nvarchar) AS [Extension_ab]
        FROM   Employees AS E

        Comment

        Working...