This is my procedure:
create proc spasdf
@sdate int,
@edate int
as
DECLARE @LoopCounter INT = @sdate
WHILE @LoopCounter <= @edate)
BEGIN
SET @LoopCounter = @LoopCounter + 1
declare @value varchar(30)
set @value = '['+@LoopCounter+']'
select UserID, UserName, @value
from vwfinal
END
I run it using:
spasdf 1,5
My expected result is:
@value=[1],[2],[3],[4],[5]
When I passing parameter to my stored procedure it shows this error
Msg 245, Level 16, State 1, Procedure spasdf, Line 40
Conversion failed when converting the varchar value '[' to data type int.
Does anyone know why?
If you want to get all the
@LoopCountervalues as a string. Declare the@valueoutside while loop and put the select statement after the while loop.The above code will append all the
@LoopCountervariable as a string along with a comma at first.using
set @value=STUFF(@value,1,1,'')we replace the first comma with a empty space.You are getting a conversion error because
@LoopCounteris of typeINTand you are trying to append it tovarchar. If you want to do so, you have toCONVERTorCASTthe@LoopCountervariable tovarcharIf you have an older version of SQL Server you can go for traditional way of appending and creating the required string format as below: