Santanu Maulik
Santanu Maulik

Reputation: 111

Varchar to Int Conversion Error In Cursor Example

First time I am trying cursor but getting the error for the varchar data type only. Error is "Conversion failed when converting the varchar value 'SGS' to data type int"

In my table StationID is INT and Station is VARCHAR.

I have written this code to show I am able to print the int, but when I try with the varchar I am unable to print.

DECLARE @vStationID INT, @vStation VARCHAR(50)
DECLARE MyCursor CURSOR
FOR 
SELECT StationID, Station FROM TblStation WHERE StationID='2'
OPEN MyCursor  
FETCH NEXT FROM MyCursor
INTO @vStationID,@vStation
PRINT @vStationID+' '+CONVERT(VARCHAR,@vStation)
CLOSE MyCursor
DEALLOCATE MyCursor

Please tell me what is the error in my code?

Upvotes: 0

Views: 979

Answers (1)

Azar
Azar

Reputation: 1867

Try this

DECLARE @vStationID INT, @vStation VARCHAR(50)
DECLARE MyCursor CURSOR
FOR 
SELECT StationID, Station FROM TblStation WHERE StationID='2'
OPEN MyCursor  
FETCH NEXT FROM MyCursor
INTO @vStationID,@vStation
PRINT convert(varchar,@vStationID)+' '+@vStation
CLOSE MyCursor
DEALLOCATE MyCursor

Upvotes: 1

Related Questions