我在SQL Server中编写了以下函数:
ALTER FUNCTION dbo.fnFormatMessage
(@Message varchar(max), @Thought varchar(max))
RETURNS varchar
BEGIN
DECLARE @FinalMessage AS varchar(max) = ' '
SELECT
@FinalMessage = LTRIM(RTRIM(CASE WHEN LEN(RTRIM(LTRIM(CONVERT(VARCHAR(MAX),ISNULL(@Thought,''))))) > 0 THEN
CASE WHEN SUBSTRING(CONVERT(VARCHAR(MAX), ISNULL(@Message,'')), LEN(CONVERT(VARCHAR(MAX), ISNULL(@Message,''))) , 1) IN ('?','!', '.')THEN
CONVERT(VARCHAR(MAX), ISNULL(@Message,''))
ELSE
CONVERT(VARCHAR(MAX), ISNULL(@Message,''))
END
+ CHAR(13) + CHAR(13) + CHAR(10) +'My Thoughts: ' + CHAR(13)
+ CASE WHEN SUBSTRING(CONVERT(VARCHAR(MAX), ISNULL(@Thought,'')), LEN(CONVERT(VARCHAR(MAX), ISNULL(@Thought,''))) , 1) IN ('?','!', '.') THEN
CONVERT(VARCHAR(MAX), ISNULL(@Thought,''))
ELSE
CONVERT(VARCHAR(MAX), ISNULL(@Thought,'')) + '.'
END
ELSE
CASE WHEN SUBSTRING(CONVERT(VARCHAR(MAX), ISNULL(@Message,'')), LEN(CONVERT(VARCHAR(MAX), ISNULL(@Message,''))) , 1) IN ('?','!', '.') OR
CONVERT(VARCHAR(MAX), ISNULL(@Message,'')) = ''
THEN
CONVERT(VARCHAR(MAX), ISNULL(@Message,''))
ELSE
CONVERT(VARCHAR(MAX), ISNULL(@Message,'')) + '.'
END
END))
Return @FinalMessage
END
当我将其作为
运行时 Select dbo.fnFormatMessage('This is a message', 'This is my thought')
我期待低于输出:
This is a message
My Thought: This is my thought
但它只返回T
答案 0 :(得分:4)
将RETURNS varchar
更改为RETURNS varchar(8000)
或适当的长度。始终使用明确的长度VARCHAR