How can I make SQL Server return FALSE for comparing varchars with and without trailing spaces?

后端 未结 6 645
刺人心
刺人心 2020-12-10 12:55

If I deliberately store trailing spaces in a VARCHAR column, how can I force SQL Server to see the data as mismatch?

SELECT \'foo\' WHERE \'bar\         


        
6条回答
  •  无人及你
    2020-12-10 13:40

    From the docs on LEN (Transact-SQL):

    Returns the number of characters of the specified string expression, excluding trailing blanks. To return the number of bytes used to represent an expression, use the DATALENGTH function

    Also, from the support page on How SQL Server Compares Strings with Trailing Spaces:

    SQL Server follows the ANSI/ISO SQL-92 specification on how to compare strings with spaces. The ANSI standard requires padding for the character strings used in comparisons so that their lengths match before comparing them.

    Update: I deleted my code using LIKE (which does not pad spaces during comparison) and DATALENGTH() since they are not foolproof for comparing strings

    This has also been asked in a lot of other places as well for other solutions:

    • SQL Server 2008 Empty String vs. Space
    • Is it good practice to trim whitespace (leading and trailing)
    • Why would SqlServer select statement select rows which match and rows which match and have trailing spaces

提交回复
热议问题