1

Good day to everybody! My question is simple, I develop a SQL sp, it needs a string to caracters

USE[Fleet]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [sp_extraccion_sharedIds] @UnitSysId varchar(max)   
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    select v.UnitSysId, v.VehicleId,a.VehicleId,p.SharedVehicleId
    from Fleet..Vehicles v with  (nolock)
        join AVLStatic..Vehicles  a with  (nolock) on v.UnitSysId=a.RMUId
        join PAI..PAIVehicleShared p with  (nolock) on v.VehicleId=p.FleetVehicleId
    where v.UnitSysId in (convert(int, @UnitSysId))
    order by v.UnitSysId asc
END
GO

The SP Works like that:

EXEC sp_extraccion_sharedIds  '141298070,141292370,185244770,185246770,252979770,256986470,256991970,256923170,256919270'

But when it runs, it show me this messsage:

Msg 245, Level 16, State 1, Procedure sp_extraccion_sharedIds, Line 13
Conversion failed when converting the varchar value '141298070,141292370,185244770,185246770,252979770,256986470,256991970,256923170,256919270' to data type int.

Can you help me please? I've try to use cast, but I don't know what is my problem.

Thanks

Pரதீப்
  • 91,748
  • 19
  • 131
  • 172
Ric_hc
  • 279
  • 2
  • 13

1 Answers1

1

You can't do that, you need to split the string into individual rows then CAST it to INT

select v.UnitSysId, v.VehicleId,a.VehicleId,p.SharedVehicleId
from Fleet..Vehicles v with  (nolock)
    join AVLStatic..Vehicles  a with  (nolock) on v.UnitSysId=a.RMUId
    join PAI..PAIVehicleShared p with  (nolock) on v.VehicleId=p.FleetVehicleId
where UnitSysId  in (select value from string_split(@UnitSysId,','))
order by v.UnitSysId asc

If UnitSysId is of INT type then you don't have to do explicit conversion

I have used STRING_SPLIT function introduced in Sql Server 2016 to split the csv into individual rows. For older versions check this answer

Pரதீப்
  • 91,748
  • 19
  • 131
  • 172