patternsqlModerate
SQL PRINT statement prints nothing
Viewed 0 times
statementsqlprintsprintnothing
Problem
I don't get any output for this simple
Data supplied in sqlfiddle.
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
ENDSolution
The PRINT statement will print nothing if the expression evaluates to a null. Apparently
You could also add a filter to the SELECT to ensure that NULLs are skipped (if you want them skipped, that is):
However, if the table has no rows or if all
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.
@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.
Code Snippets
PRINT 'value is ' + ISNULL(@team, '(null)');SELECT @team = TEAM
FROM DISTRIB_LINE
WHERE TEAM IS NOT NULL;Context
StackExchange Database Administrators Q#200048, answer score: 17
Revisions (0)
No revisions yet.