2012-05-01 59 views
0

我試圖找出一個選擇語句,將字段值截斷爲100個字符,並將其添加到它的末尾如此喜歡:如何截斷一個字段並在其後面添加「...」?

HundredLetterSentence變成了HundredLetter Sen ......或類似的東西。這是我的存儲過程中的select語句。我有點從這裏陷入困境。 Select TOP(1)描述是我想要截斷的地方。

SELECT  [TI].[TicketID] 
     , CAST([TI].[Subject] AS VARCHAR(100)) [Subject] 
     , [TA].[DueDate] 
     , CAST(
        ( SELECT 
         TOP(1)  SUBSTRING(Description, 0, 100) 
         FROM  Comment 
         WHERE  TicketID = [TI].[TicketID] 
         ORDER BY CommentDate DESC 
        ) AS VARCHAR(100) 
       ) AS [Description] 
FROM  [dbo].[Ticket]  [TI] 
INNER JOIN [dbo].[Task]  [TA] 
ON   [TI].[TicketID]  = [TA].[TicketID] 
INNER JOIN [dbo].[Task_Status] [TS] 
ON   [TA].[StatusID]  = [TS].[StatusID] 
WHERE  [TI].[IsDeleted] = 0 
AND   [TS].[IsDeleted] = 0 
AND   [TS].[Status]  = 'Open' 
AND   [TI].[AssigneeView] IS NULL 
AND   [TI].[AssignedTo] = @AssignedTo 

回答

1

什麼工作是一樣的東西 -

SELECT CASE 
      WHEN (LEN(Table1.LongText) < 100) THEN Table1.LongText 
      ELSE SUBSTRING(Table1.LongText,1, 97) + '...' 
     END AS [Description] 
FROM Table1; 
+0

糟糕 - 重新閱讀帖子,看到你說「截斷爲100個字符」,我做了100個字符的總長度:)你可以用100替換97(或者任何想要剪輯的長度 –

1

我認爲這裏最好的方法是創建一個User Defined Function(UDF)。

在這個UDF,你會碰到這樣的:

IF LEN(@Value)>100 
BEGIN 
    SET @Value = SUBSTRING(@Value, 0, 100) + '...' 
END 
RETURN @Value 

然後在你的SELECT聲明,你會怎麼做:

SELECT [TI].[TicketID], dbo.TruncateString([TI].[Subject]) ..... 
+3

我其實不會在SELECT列表推薦UDF執行一個簡單的字符串操作。爲什麼?那麼,啓動一個跟蹤,看看當你對多行的表進行操作時會發生什麼。 :-) –

0
;WITH x (d, tid, rn) AS 
(
    SELECT SUBSTRING(Description, 1, 100) + CASE 
    WHEN LEN(Description) > 100 THEN '...' ELSE '' END, 
    TicketID, rn = ROW_NUMBER() OVER 
    (PARTITION BY TicketID ORDER BY CommentDate DESC) 
    FROM dbo.Comment 
) 
SELECT [TI].[TicketID], 
    CAST([TI].[Subject] AS VARCHAR(100)) [Subject], 
    [TA].[DueDate], 
    x.d AS [Description] 
    FROM  [dbo].[Ticket] [TI] 
      INNER JOIN [dbo].[Task] [TA] ON [TI].[TicketID] = [TA].[TicketID] 
      INNER JOIN [dbo].[Task_Status] [TS] ON [TA].[StatusID] = [TS].[StatusID] 
    LEFT OUTER JOIN x ON TI.TicketID = x.tid 
    AND x.rn = 1 -- oops, forgot this important part 
    WHERE [TI].[IsDeleted] = 0 AND 
      [TS].[IsDeleted] = 0 AND 
      [TS].[Status] = 'Open' AND 
      [TI].[AssigneeView] IS NULL AND 
      [TI].[AssignedTo] = @AssignedTo; 
0

做你需要所有的領域有'...'或者只有那些實際上大於100個字符的領域。 如果你需要的一切,你可以這樣做:

select substring(name,0,97)+'...' from... 
相關問題