如何在开头,结尾或两个空格之间删除逗号?
例如:
DECLARE @str NVARCHAR(max)=N' , test1 '; select * from functionReplace(@str) =N'test1;
SET @str = '1 , 2 ,';select * from functionReplace(@str) =N'1 , 2';
SET @str = ', ';select * from functionReplace(@str) = empty=N'';
你能帮我写一个函数吗?
答案 0 :(得分:2)
在这里,您可以找到具有标量函数的解决方案。与您的预期产出的唯一区别是" 1,2"来到" 1 2" ...
CREATE FUNCTION dbo.functionReplaceComma(@str NVARCHAR(MAX))
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN (SELECT LTRIM(RTRIM(REPLACE(N' ' + @str + N' ',N' , ',N' '))));
END
GO
SELECT dbo.functionReplaceComma(N', this is , a test , with commas word1, word2, in between and at start and ending ,');
--this is a test with commas word1, word2, in between and at start and ending
SELECT dbo.functionReplaceComma(N' , test1 ');
--test1
SELECT dbo.functionReplaceComma(N'1 , 2 ,');
--1 2
SELECT dbo.functionReplaceComma(N', ');
--empty