Why does sql server print prints nothing?

384    Asked by AlisonKelly in SQL Server , Asked on Oct 4, 2022

I don't get any output for this simple PRINT statement. What am I missing?


Data supplied in sqlfiddle.
DECLARE @team varchar(20)
BEGIN
   SELECT @team = TEAM
   FROM DISTRIB_LINE 
   PRINT 'value is' + @team

END

Answered by Amanda Hawes

The sql server PRINT statement will print nothing if the expression evaluates to a null. Apparently @team ends up being null as the result of the preceding statement, causing the PRINT to output nothing. If you want to print something even when the variable is null, use ISNULL or COALESCE:


PRINT 'value is ' + ISNULL(@team, '(null)');
You could also add a filter to the SELECT to ensure that NULLs are skipped (if you want them skipped, that is):
SELECT @team = TEAM
FROM DISTRIB_LINE 

WHERE TEAM IS NOT NULL;However, if the table has no rows or if all TEAM values are null, this statement will not do any assignment. In this case, if PRINT still outputs nothing, it means @team was null even before the SELECT. Therefore, you may still need to apply the previous method.

Besides, it is not a good idea to assign a variable this way when a table has many rows, because you have no control of which value will ultimately be assigned. Therefore, Alexei has a point there as well with regard to using TOP, as well as combining it with ORDER BY and, possibly, additional filters.



Your Answer

Interviews

Parent Categories