TSQL PRINT statement conversion issue

13,787

You should CAST your variables as nvarchar first:

DECLARE @COUNT INT, @CONST INT
SET @COUNT = 0
SET @CONST = 12

WHILE(@COUNT<12)
BEGIN
    SET @COUNT = @COUNT + 1
    PRINT CAST(@COUNT as nvarchar) + N' times ' + CAST(@CONST as nvarchar) + N' is ' + CAST(@COUNT*@CONST as nvarchar)
END
Share:
13,787
Hanna
Author by

Hanna

Updated on August 05, 2022

Comments

  • Hanna
    Hanna almost 2 years

    When I try to print a line with int and nvarchar in a single line I get an error. Here's the entirety of my code.

    DECLARE @COUNT INT, @CONST INT
    SET @COUNT = 0
    SET @CONST = 12
    
    WHILE(@COUNT<12)
    BEGIN
        SET @COUNT = @COUNT + 1
        PRINT @COUNT + N' times ' + @CONST + N' is ' + @COUNT*@CONST
    END
    

    The error I get is:

    Msg 245, Level 16, State 1, Line 8 Conversion failed when converting the nvarchar value ' times ' to data type int.

    I can print 'int' a nvarchar just find on their own, but when I combine them I get this error. Am I improperly combining them?

    I'm using Microsoft SQL Management Studio

  • Hanna
    Hanna almost 13 years
    Ahh, I had my suspicious about casting. Thank you :]