sql server-adding a suffix to an integer field

Yacovs 1 Reputation point
2021-03-31T19:16:23.257+00:00

I would like to display an Integer type field (Salary in this example) with a symbol suffix (%)
To do this I've cast it as a varchar, with the varchar size the maximum current length of the field (5)
However, what I would really like is to have the varchar size be programmatically the length of the field

SELECT
[salary]
,len(salary) LenSalary
,cast(salary as varchar(5))+'%' 'Salary+%'
--,cast(salary as varchar(len(salary)))+'%'

salary LenSalary Salary+%
10,000 5 10000%

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,547 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Erland Sommarskog 100.8K Reputation points MVP
    2021-03-31T21:41:19.023+00:00

    Why?

    If it is an integer column, go for varchar(10), as that is long as an integer value can be. Well, 11 if it is negative. Or simply say

    select concat(Salary, ' %')
    
    1 person found this answer helpful.
    0 comments No comments

  2. EchoLiu-MSFT 14,571 Reputation points
    2021-04-01T06:22:02.653+00:00

    Hi @Yacovs ,

    Is the length of each data in your salary column the same? I guess it should be different. If the length of each data in the salary column is the same, that is, a fixed value, then you can try:

        select len(salary) LenSalary from yourtable   
    

    then:

        select cast(salary as varchar(The fixed value from the previous step))+'%' from yourtable   
    

    But this should not be the case.The actual length of each value in your salary column should be different, and the parameter in varchar can only be a fixed value, so your idea cannot be realized.

    Please also try:

    select cast(salary as varchar)+'%' from yourtable  
    

    If you have any question, please feel free to let me know.
    If the response is helpful, please click "Accept Answer" and upvote it.

    Regards
    Echo


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments