2013-04-09 61 views
3

我的數據庫中有一個字段,爲了報告目的,我打算使用下面的語句將其截斷爲50個字符。使用SUBSTRING和CHARINDEX獲取字段中的最後一個完整字

SELECT (CASE WHEN (LEN(Notes) > 50) THEN SUBSTRING(Notes, 0, 50) + '...' WHEN (LEN(Notes) < 50) THEN SUBSTRING(Notes, 0, LEN(Notes)) + '...' ELSE 'NO NOTES WERE ENTERED' END) AS Notes FROM MyTable 

這個偉大的工程,但是,我想完成在備註字段的最後一個字,這樣一個詞是不切斷,所以我想用CHARINDEX,SUBSTRING,扭轉和可能正確的函數返回大約50個字符長度的字符串中最後一個完整的單詞。

我已經嘗試過,沒有多少運氣。

任何幫助,將不勝感激。

回答

3

如果筆記列的長度超過50,則可以使用CHARINDEX查找位置50之後的下一個空格,並找到該位置的SUBSTRING。這是一個SQL Fiddle

SELECT RTRIM(
    CASE 
     -- when the length is less than 50, or the character at position 50 is part of the last word, return the entire string 
     WHEN LEN(notes) < 50 OR (SUBSTRING(notes,50,1) <> ' ' AND CHARINDEX(' ',notes,50) = 0) 
      THEN notes 
     -- when the character at position 50 is a space, return the first 50 characters of the string 
     WHEN SUBSTRING(notes,50,1) = ' ' 
      THEN LEFT(notes, 50) 
     -- when the character at position 50 is a word, cut off the string at the next space after 50 
     WHEN SUBSTRING(notes,50,1) <> ' ' 
      THEN LEFT(notes,CHARINDEX(' ',notes,50)) 
    END) AS first_50 
FROM tbl_notes 
+0

這個工作預期。非常感謝! – user2146538 2013-04-09 22:22:04

+0

現在,如果您也將他的答案標記爲正確,那麼他會因發佈答案而獲得一點積分。 – BerggreenDK 2013-08-21 12:24:28

0

如果你不想超出字符數限制,你可以有這樣的:

DECLARE @Table TABLE 
(
    String nvarchar(100) 
) 

DECLARE 
    @Size int    = 25 

INSERT @Table SELECT 'Lorem ipsum dolor sit ame' 
INSERT @Table SELECT 'Lorem ipsum dolor sit ame tas' 
INSERT @Table SELECT 'Lorem ipsum dolor sit am asd' 
INSERT @Table SELECT 'Lorem ipsum dolor sita am' 
INSERT @Table SELECT 'Lorem ipsum dolor sita a amet, consectetur adipiscing elit,' 
INSERT @Table SELECT 'Lorem ipsum dolor sita' 
INSERT @Table SELECT 'Lorem ipsum dolor sita asamet, consectetur adipiscing elit,' 

SELECT 
    LEN(R.LimitTruncation) AS LimitTruncationLen, 
    R.LimitTruncation, 
    LEN(String) AS StringLen, 
    R.String 
FROM 
(
    SELECT 
    String, 
    --This is the main part 
    CASE 
     WHEN LEN(String) <= @Size THEN String 
     WHEN CHARINDEX(' ', String, @Size) = @Size OR CHARINDEX(' ', String, @Size) = @Size + 1 THEN RTRIM(LEFT(String, @Size)) 
     ELSE REVERSE(SUBSTRING(REVERSE(LEFT(String, @Size)), CHARINDEX(' ', REVERSE(LEFT(String, @Size))), @Size)) 
    END AS LimitTruncation 
    FROM 
    @Table 
) R 
相關問題