Sqlserver
 SQL >> Database >  >> RDS >> Sqlserver

LEFT/RIGHT contro SUBSTRING in T-SQL: la trappola degli spazi finali

Hai degli spazi finali. È tutta qui la faccenda.

RIGHT restituisce tranquillamente quegli spazi, mentre LEN li ignora: ecco perché le due funzioni non sono d'accordo su dove finisce la stringa.

DECLARE @foo varchar(100) SET @foo = 'abc12345def ' --3 spaces --right or substring SELECT RIGHT(@foo, 3) SELECT SUBSTRING(@foo, LEN(@foo)-2, LEN(@foo)) --demonstrate you get spaces SELECT REPLACE(RIGHT(@foo, 3), ' ', 'z') --single space --length differences SELECT LEN(@foo), DATALENGTH(@foo) --solution SELECT RIGHT(RTRIM(@foo), 3) --or trim your column values before storing 

Nota che DATALENGTH e LEN che restituiscono numeri diversi è il segnale rivelatore. Vedi SET ANSI_PADDING per capire perché il riempimento è stato memorizzato in primo luogo.

E per essere chiari, non otterrai NULL da un input non-NULL:

--only NULL if you send in NULL SELECT RIGHT(NULL, 3)