What's a good way to trim all whitespace characters from a string in T-SQL without UDF and without CLR?

前端 未结 2 2109
抹茶落季
抹茶落季 2020-11-27 23:41

The .NET function string.Trim trims a rather extensive set of whitespace characters. How would this exact behavior be emulated in the best way T-SQL?

2条回答
  •  失恋的感觉
    2020-11-27 23:46

    I'll be interested to see if anyone finds a generic SQL solution.

    The best I can come up with is a simple REPLACE function:

    SELECT MyString = LEFT(MyString, LEN(RTRIM(REPLACE(REPLACE(REPLACE(MyString COLLATE Latin1_General_100_BIN2, NCHAR(9), ' '), NCHAR(12), ' '), NCHAR(13), ' ')))) AS RTrimmed
    
    SELECT MyString = RIGHT(MyString, LEN(LTRIM(REPLACE(REPLACE(REPLACE(MyString COLLATE Latin1_General_100_BIN2, NCHAR(9), ' '), NCHAR(12), ' '), NCHAR(13), ' ')))) AS LTrimmed
    

    etc.

    You can get the list of current whitespace characters here:

    http://unicode.org/charts/uca/chart_Whitespace.html

    Or, to prove it to yourself, you could export a list of all characters from SQL Server to something like Excel, clean the characters, and import them back in. Whatever was removed was whitespace.

提交回复
热议问题