I want to print table of 17 from 3 to 17 but my code throws error not converting 'x' and '=' into int

33 Views Asked by At
declare @table int
set @table = 17

declare @loop int
set @loop = 3

declare @x varchar
set @x = 'x'

while(@loop <= 17)
begin
    print @table + cast(@x as varchar) + @loop + cast(' = ' as char) + @table * @loop
end

In this code you see @x and '=' which is not converting into int.

I get this error instead:

Msg 245, Level 16, State 1, Line 67
Conversion failed when converting the varchar value 'x' to data type int.

I tried to convert @x to int as well as I changed data type of variable but it didn't work so far.

So I tried to put values of x and = into variables and change datatype on earlier stage but same problem occurred every time

1

There are 1 best solutions below

1
Muhammad Yahya On
declare @table int
set @table=17
declare @loop int
set @loop=3

while(@loop<=17)
begin
    print concat( @table ,'x',+@loop,'=', +@table*@loop)
    set @loop+=1
end

When I see problem I got an mistake on print statement where I was using only variables but I didn't realize they all should have same datatype that what the problem I thought so I researched for concat keyword. it automatically converts all variables and values in between to datatype that is being required so I used

print concat(@table ,'x',+@loop,'=', +@table*@loop)