SQL语法强制转换函数

时间:2018-05-23 16:50:50

标签: sql sql-server

我有这个代码,我首先需要找到ENROLL_PERIOD最低的学生,然后找到join grades表的学生。问题是我的表students中的数据存储为文本。因此,在我正确排序数据之前,我需要使用cast函数,并使表ENROLL_PERIOD中的students成为整数。但是我应该把它放在代码中?我一直在收到语法错误。希望有人可以帮助我!

2 个答案:

答案 0 :(得分:0)

我相信你想要:

Select *
from (select top (100) s.*
      from students s 
      where PERSON_ID <> ''
      order by TRY_CAST(KonvENROLL_PERIOD AS INT)   
     ) s 
join grades g
  on s.PERSON_ID = g.PERSON_ID

答案 1 :(得分:0)

该列属于select。另外,使用try_cast()来避免错误:

Select *
from (select top (100) s.*, try_cast(ENROLL_PERIOD AS int) AS KonvENROLL_PERIOD
      from students s 
      where PERSON_ID <> '' 
      order by KonvENROLL_PERIOD ASC      
     ) s inner join
     grades g
     on s.PERSON_ID = g.PERSON_ID;