Home > OS >  PRINT Statement in MSSql
PRINT Statement in MSSql

Time:08-04

Simple I need to print 4 varchar variables

 @divisionId,@Divisionname,@isActive,@Divcode

above are variables.

 PRINT  @divisionId,@Divisionname,@isActive,@Divcode

ERROR

Msg 102, Level 15, State 1, Line 15
Incorrect syntax near ','.

showing error . please help me out

CodePudding user response:

I usually find it easiest to output multiple values in a single print statement using concat as it automagically casts types to string:

print concat('p1=', @p1, ', p2=', @p2...);

CodePudding user response:

You can use four separate statements:

 PRINT  @divisionId
 PRINT  @Divisionname
 PRINT  @isActive
 PRINT  @Divcode

Or you can use string concatenation as below:

PRINT  cast(@divisionId as varchar) ','  @Divisionname  ','  cast(@isActive as varchar) ',' @Divcode

I assumed that @divisionId and @isActive is not of varchar type. So I have converted those into varchar.

CodePudding user response:

PRINT is an alternative of RAISERROR function. Both are meant to send strings to console output.

This means a single number is implicitly converted to nvarchar. And this causes the error when trying to send multiple numbers. As this is clearly not a single string. CONCAT helps because again it uses implicit Casts to accomplish the conversion.

For debugging I use

DECLARE @mystring  nvarchar(2000)
;
SET @mystring = ...string conversion and concatenation work here...
;
RAISERROR( @mystring, 0, 1 ) WITH NOWAIT
;

Unlike PRINT which outputs after the whole statement ends this way drops console output during the execution. Excellent to figure out where in a long procedure(s) execution the execution stands and for evaluating some critical transformations while those happen.

  • Related