我正在试图找出一个将字段值截断为100个字符的select语句,并将...添加到它的末尾,如下所示:
HundredLetterSentence变成了HundredLetter Sen ......或类似的东西。这是我的存储过程中的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
答案 0 :(得分: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]) .....
答案 1 :(得分:1)
什么会起作用 -
SELECT CASE
WHEN (LEN(Table1.LongText) < 100) THEN Table1.LongText
ELSE SUBSTRING(Table1.LongText,1, 97) + '...'
END AS [Description]
FROM Table1;
答案 2 :(得分: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;
答案 3 :(得分:0)
你是否需要所有字段都有'...'或者只有那些实际上超过100个字符的字段。 如果您需要所有,您可以执行以下操作:
select substring(name,0,97)+'...' from...