0

我正在尝试找出一个 select 语句,它将字段值截断为 100 个字符并将 ... 添加到它的末尾,如下所示:

HundredLetterSentence 变成 HundredLetter Sen... 或类似的东西。这是我的存储过程中的 select 语句。我从这里有点卡住了。Select TOP(1) Description 是我想要截断的地方。

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
4

4 回答 4

1

我认为这里最好的方法是创建一个用户定义函数(UDF)。

在这个 UDF 中,您将有类似的内容:

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

然后在你的SELECT声明中你会这样做:

SELECT [TI].[TicketID], dbo.TruncateString([TI].[Subject]) .....
于 2012-05-01T16:24:28.030 回答
1

什么会起作用是这样的 -

SELECT CASE 
           WHEN (LEN(Table1.LongText) < 100) THEN Table1.LongText
           ELSE SUBSTRING(Table1.LongText,1, 97) + '...'
       END AS [Description]
FROM Table1;
于 2012-05-01T16:42:15.237 回答
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;
于 2012-05-01T16:37:00.753 回答
0

您是否需要所有字段都具有“...”或仅需要实际大于 100 个字符的字段。如果您需要全部,您可以执行以下操作:

select substring(name,0,97)+'...' from...
于 2012-05-01T16:50:46.247 回答