Sunday, February 19, 2012

How to build an string alias in T-SQL

I have the following stored procedure:

SELECT

SERVER_NAME,

SERVICE_PORT,

SERVER_NAME + ',' + SERVICE_PORT

ASSERVER_AND_PORT

FROM

DEF_SERVICE_SETTINGS

I want the 3rd column to be in format: SERVER_NAME + "," + SERVICE_PORT

But SQL gives error. Sees "," as column.

How can I fix this?

Which database and language you are using?|||

SQL-server

Column SERVER_NAME is varchar type
Column SERVICE_PORT is int type

|||

My code works when both type of columns are of varchar, but the SERVICE_PORT column is of int type.

Can I cast the int type to a varchar type in some way?

|||

Found it:

SERVER_NAME +','+CAST(SERVICE_TCP_PORTAs varchar(1000))ASSERVER_AND_PORT

|||

Yes you have to Cast.

SERVER_NAME + ',' + Cast(SERVICE_PORT as varchar) AS SERVER_AND_PORT

|||convert(varchar(50), SERVICE_PORT)

HTH

No comments:

Post a Comment