Roy
Roy

Reputation: 11

SQL result with background color

I am trying to return a count result with background color depending on the amount of existing elements in a table.

MS SQL

DECLARE @cc int
SET @cc = (SELECT COUNT(*) FROM PROBLEMS)

SELECT
CASE WHEN @cc>10 THEN concat("<div style='background-color: red'>",cast (@cc as char),"</div>") 
ELSE concat("<div style='background-color: green'>",cast (@cc as char),"</div>")
END
FROM PROBLEMS

Any ideas how to fix my query ?

Upvotes: 0

Views: 8684

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

First, don't use char without a length.

Second, you don't need variables for this. Just run the query:

SELECT (CASE WHEN COUNT(*) > 10 THEN '<div style=''background-color: red''>'
             ELSE '<div style=''background-color: green''>'
        END) + CAST(COUNT(*) as varchar(255)) + '</div>'
FROM PROBLEMS;

Notes:

  • Single quotes are used to delimit strings in SQL, not double quotes (some other databases do support double quotes for this purpose, but that is an extension).
  • For a single quote in a string, double it up '' (not ").
  • Always use a length for the character type.
  • The concatenation operator in SQL Server is +, although concat() also works.

Upvotes: 1

Related Questions