如何将字符串转换为int SQL Server(存储过程)
大家好!我的问题很简单,我开发了一个SQL sp,它需要一个字符串来表示字符如何将字符串转换为int SQL Server(存储过程),sql,sql-server,sql-server-2008,tsql,Sql,Sql Server,Sql Server 2008,Tsql,大家好!我的问题很简单,我开发了一个SQL sp,它需要一个字符串来表示字符 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 -- int
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
SP的工作原理如下:
EXEC sp_extraccion_sharedIds '141298070,141292370,185244770,185246770,252979770,256986470,256991970,256923170,256919270'
但当它运行时,它会向我显示以下信息:
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.
你能帮我吗?我试着使用cast,但我不知道我的问题是什么
谢谢您不能这样做,您需要将字符串拆分为单独的行,然后将其转换为
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
如果UnitSysId
是INT
类型,则不必进行显式转换
我使用了Sql Server 2016中引入的函数将csv拆分为单独的行。对于旧版本,请选中此项可能重复。考虑使用TVP而不是使用CSV值的VARCHAR(MAX)。尝试使用<代码>(‘+@ UNITSIDS++’)<代码>代替<代码>(转换(int,@ UnitSysId))< /代码>我尝试它,失败!!!!但是谢谢你,雷福@你到底做了什么?你收到错误信息了吗?您使用的是哪个版本的Sql Server?我使用的是string_split,var@UnitSysId是int,但是,参数是int,我需要在“,”中分隔它。哦,您是对的!!打扰一下我的SQL版本是2008年。对不起@Ric_hc-从我共享的链接创建函数,并使用它而不是
string_split