1

我想转换值

2to5experience

3to7experience

到Minexperience:

2
3

最大经验

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时转换失败”

任何的想法?

4

2 回答 2

2

在您选择的倒数第二行中,您将表达式转换为int然后添加(使用+) a )。由于左侧的值+是整数,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

笔记:

Experienceto的演员varchar阵容可能是多余的。

于 2013-04-16T08:27:36.007 回答
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
于 2013-04-16T10:00:06.240 回答