使用patindex在select语句中将varchar转换为int

时间:2013-04-16 11:00:57

标签: sql-server casting substring patindex

我的查询是将varchar转换为字符串,

select top(5)'Insert into jobs(minexperience,maxexperience)values('+

cast(substring(Experience as varchar(50)),0,patindex('%to%',Experience))*365*24*60*60,

cast(substring(Experience as      

varchar(50)),patindex('%to%',Experience)+2,patindex('%Years%',Experience)-patindex('%to%',Experience)-2)*365*24*60*60+')'

from requirementsdetailsfororganization

在我的以下查询中,我在关键字'AS'附近有错误“语法不正确。”

我想将字符串转换为整数。

任何帮助?

1 个答案:

答案 0 :(得分:2)

这对你有帮助 -

SELECT TOP(5) 'INSERT INTO dbo.jobs(minexperience,maxexperience) VALUES(' +
    CAST(SUBSTRING(
          CAST(r.Experience AS VARCHAR(50))
        , 0
        , r.ToExperience) * 31536000 
    AS VARCHAR(50))

    + ',' +

    CAST(SUBSTRING(
          CAST(r.Experience AS VARCHAR(50))
        , r.ToExperience + 2
        , patindex('%Years%', r.Experience) - r.ToExperience - 2) * 31536000 
    AS VARCHAR(50))
+')'
FROM (
    SELECT 
          r.Experience
        , ToExperience = PATINDEX('%to%', r.Experience)
    FROM dbo.requirementsdetailsfororganization r
) r