0

I'm coding a SQL Server query that queries hard drive information from a series of computers and highlights the drives with less than 20% capacity. I'd like to make the ones with 10% or less capacity yellow. I'm using a case statement in my query and I'm having trouble with the syntax.

CASE 
   WHEN ((UsedSpace/CAST(TotalSpace as decimal(18,2))) > 0.9) 
      THEN CAST('''<font color="yellow">'' + [FreeSpace] + ''</font>''' AS varchar(150)) 
      ELSE [FreeSpace] 
END AS 'td',

This causes an error:

Conversion failed when converting the varchar value ''' + [FreeSpace] + ''' to data type int.

1
  • This like means that the output of the CASE expression is an integer value. You've got a CASE condition that returns CHAR data instead. Make sure each WHEN clause returns Character data Commented Jun 14, 2021 at 16:35

1 Answer 1

3

You're mixing data types... INT and Strings

Assuming you are creating and HTML Table, one option is to use concat() and XML. concat() is an easy way to mix data types without having to be concerned with conversions.

Example

Declare @yourtable table (UsedSpace int,TotalSpace int,FreeSpace int)
Insert into @YourTable values 
 ( 95,100,5)
,( 80,100,20)

Select 

 CASE WHEN ((UsedSpace/CAST(TotalSpace as decimal(18,2))) > 0.9) 
      THEN convert(XML,concat('<font color="yellow">',[FreeSpace],'</font>'))
      ELSE concat('',FreeSpace) END as 'td'
 From @YourTable
 For XML Path('tr')

Results

<tr>
  <td>
    <font color="yellow">5</font>
  </td>
</tr>
<tr>
  <td>20</td>
</tr>
Sign up to request clarification or add additional context in comments.

1 Comment

@alcor8 Always happy to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.