用于拆分字符串的SQL Query

时间:2015-07-24 07:02:42

标签: sql db2

我有一个名为"座位编号"的列表。值将类似于ABCD 4F A083,XYZ 3F 7098。我想将字符串拆分为三个单独的字符串,并需要与其他表列值进行比较。我试过这样但得到错误,你能帮我解决这个问题吗?

查询:

SELECT A.EMPLOYEE_NAME,
       Substr(A.EMPLOYEE_CODE, 1, 6) AS "EMPLOYEE_CODE",
       A.EMPLOYEE_NOTES_ID,
       A.ACCOUNT_SECTOR,
       A.ACCOUNT_INDUSTRY,
       A.GLOBAL_CLIENT_NAME,
       A.PROJECT_DB_ID,
       A.PROJECT_NAME,
       B.WORKPLACE_INDICATOR,
       B.SPACE_ID,
       C.FLOCATION,
       D.FBUILDING
FROM   DB2INST1.TMP_PIR A
       INNER JOIN DB2INST1.BluePages B
               ON Substr(A.EMPLOYEE_CODE, 1, 6) = B.EMP_CODE
       LEFT OUTER JOIN DB2INST1.TPARAM_LOCATION C
                    ON A.LOCATION_AS_PER_BLUEPAGES = C.FLOCATION
       LEFT OUTER JOIN DB2INST1.TPARAM_BUILDING D
                    ON LEFT(B.SPACE_ID, Charindex('', B.SPACE_ID) - 1) = D.FBUILDING 

值由"空格键"

分隔

1 个答案:

答案 0 :(得分:0)

首先,我们需要弄清楚我们需要的关键值。所以你需要找到每个空间的位置(第一次和第二次出现)。

first_occurence_location = CHARINDEX ( ' ' ,Space_ID) 

second_occurence_location = CHARINDEX ( ' ' , Space_ID, CHARINDEX ( ' ' ,Space_ID))

接下来,您需要找到空格之间的值:

first_value = SUBSTRING(Space_ID, 0, first_occurence_location)

second_value = SUBSTRING(Space_ID, first_occurence_location, second_occurence_location - first_occurence_location)

third_value = SUBSTRING(Space_ID, second_occurence_location, len(Space_ID)-second_occurence_location)

所以最终的结果是:

select 
   SUBSTRING(Space_ID, 0, CHARINDEX ( ' ' ,Space_ID) ) as first_value, 
   SUBSTRING(Space_ID, CHARINDEX ( ' ' ,Space_ID) , CHARINDEX ( ' ' , Space_ID, CHARINDEX ( ' ' ,Space_ID)) - CHARINDEX ( ' ' ,Space_ID) ) as second_value,
   SUBSTRING(Space_ID, CHARINDEX ( ' ' , Space_ID, CHARINDEX ( ' ' ,Space_ID)), len(Space_ID)-CHARINDEX ( ' ' , Space_ID, CHARINDEX ( ' ' ,Space_ID))) as third_value
from table