Monday, 17 July 2017

MSSQL - Fix Error - Conversion failed when converting the varchar value 'Select * from Cities where ID = ' to data type int.

 Watch this on YouTube



Msg 245, Level 16, State 1, Line 5
Conversion failed when converting the varchar value 'Select * from Cities where ID = ' to data type int.


to fix it replace

Declare @ID int = 1

Declare @SQL varchar(max)

Set @SQL = 'Select * from Cities where ID = ' +  @ID

exec (@SQL)

with

Declare @ID int = 1

Declare @SQL varchar(max)

Set @SQL = 'Select * from Cities where ID = ' + CAST( @ID AS VARCHAR)

exec (@SQL)