Oracle PL/SQL Tips : How to query first and last word in any string
Oracle PL/SQL Tips : How to query first and last word in any string
วันนี้มีเกล็ดเกี่ยวกับการจัดการข้อความมาฝากครับ เป็นวิธีการหาข้อความจากประโยค โดยในทีนี้จะนำเสนอการตัดข้อความแรก (first word) และข้อความสุดท้าย (last word) จากประโยค
โดยสมมติว่ามีตาราง TEST_STRING ที่เก็บประโยคดังนี้
SQL> select text from test_string;
TEXT he broken legs she make billion us dolla |
ในการตัดข้อความ string ใดๆเราจะใช้ฟังก์ชัน “SUBSTR()” ซึ่งมีรูปแบบดังนี้
?SUBSTR(<Text>, <first position>, [<end position>])? |
ดังนั้น เราจะได้ Statetment ดังนี้
?SELECT SUBSTR(TEXT,1,INSTR(TEXT,’ ‘)-1) First_Word , SUBSTR(TEXT,INSTR(TEXT,’ ‘,-1)+1) Last_Word FROM TEST_STRING ; ? |
ได้ผลลัพธ์ดังนี้
FIRST_WORD LAST_WORD —————————— —————————— somchai man he legs she dolla |
ลองทดสอบดูครับ