I’m trying to figure out how to handle an error that gets thrown at the final set statement, wherein I call substring on the current @return value and set the result the same return value.
The stored procedure takes in a string of numbers like this: ‘135, 34, 21,’. The trailing comma is an artifact of a poorly designed system. This procedure runs the string through a split function to create a temp table, and then does a look up on each of the items in the string, returning a name associated with each of the three values. The error is thrown when all three values of the parameter are 0: ‘0,0,0,’
I’m just crap with SQL Server and have no idea how to gracefully handle those situations. Could someone provide some advice for me?
Here is my stored procedure:
declare @positions table
(orderID int identity(1,1), positionID int)
declare @counter int
declare @positionMax int
declare @currentPositionID int
declare @return varchar(max)
set @counter = 1
set @return = ''
insert @positions
select items
from dbo.Split(
(select Positions
from dbo.athletes
where athleteID = 3701, ',')
select @positionMax = max(orderID)
from @positions
while(@counter <= @positionMax)
begin
select @currentPositionID = tp.PositionID
from db.positions tp
inner join @positions p
on tp.PositionID = p.positionID
where p.orderID = @counter
select @return = @return + PositionName + ', '
from dbo.positions
where PositionID = @currentPositionID
set @counter = @counter + 1
end
set @return = substring(@return, 1, (len(@return) - 1))
select @return
Edit with sample data and expected results
Here’s what the positions table looks like:
PositionId, PositionName
1, Defensive End
2, Quarterback
3, Pitcher
4, Catcher
5, First Base
The positions are saved in a single table row like this:
1,2,3,
1,0,0,
0,0,0,
The output would look like this:
Defensive End, Quarterback, Pitcher Defensive End No position selected
“No position selected” is what I’d like to have output in the instance of three zeros.
I’m guessing your error is caused because @return is 0 characters long. A simple option could be to add the value 0, ‘No position selected’ to the positions table.
A nicer option could be to add an IF statement around the set statement:
You could also add a Try/Catch block if using SQL to catch any generic exceptions. See msdn try/catch
Also, not sure why you’re doing the while loop. There are generally better options in SQL like using a CTE.