创建选择查询如何使用强制转换将varchar转换为int

时间:2013-04-16 08:20:59

标签: sql sql-server-2008 select casting substring

我想转换值

2to5experience

3to7experience

要 Minexperience:

2
3

Maxexperience

5
7

所以我创建了以下查询,

select cast(substring(Cast(Experience AS VARCHAR(50)),1,1)*365*24*60*60 as int) as Experience 
      from requirementsdetailsfororganization

上面的工作正在进行中。当我像下面这样更新查询时,我收到一个错误。

select 'Insert into Jobs(requirementId,organizationId,Minexperience)values(' + 
   Cast(o.RequirementID as varchar(50))+',' +
   Cast(o.OrganizationID as varchar(50))+',' +
   cast(substring(CAST(Experience AS VARCHAR(50)),1,1)*365*24*60*60 as int)+')'
   FROM RequirementsDetailsforOrganization AS o

显示错误

转换varchar值时转换失败')'到数据类型int”

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

在您选择的倒数第二行中,您将表达式转换为int,然后添加(使用+)。由于+左侧的值是整数,因此SQL Server会尝试将+右侧的操作数转换为整数。

尝试将广播组件更改为int,以便您将其转换为varchar

select 'Insert into Jobs(requirementId,organizationId,Minexperience)values(' + 
   Cast(o.RequirementID as varchar(50))+',' +
   Cast(o.OrganizationID as varchar(50))+',' +
   cast(substring(CAST(Experience AS VARCHAR(50)),1,1)*365*24*60*60 as varchar(50))+')'
   FROM RequirementsDetailsforOrganization AS o

注意:

Experiencevarchar的演员可能是多余的。

答案 1 :(得分:1)

尝试以下步骤。

--Create Table :
Create Table #Table
(
Name Varchar(50),
Experience Varchar(20)
)
Go

-- Insert Values :
Insert into #Table Values('Tom','0to0experience')
Insert into #Table Values('Victor','0to1experience')
Insert into #Table Values('Mark','11to12experience')
Go

--View Data
Select  * from #Table

--Using CharIndex  and Substring :
Select Name,
Substring(Experience,1,CharIndex('to',Experience)-1) as Yearfrom,
Substring(Experience,(CharIndex('to',Experience)+2),Len(Replace(Experience,'experience','')) - (CharIndex('to',Experience)+1)) as YearTo
from #Table

--Clean Up:
Drop Table #Table