Comparison of NVarChar Variables

Perhaps this is really stupid. I really don't understand the comparison of NVarChar in T-SQL .. if I try something like this:

DECLARE @A NVARCHAR = 'A'; DECLARE @AB NVARCHAR = 'AB'; if @A = @AB BEGIN PRINT N'A EQUALS AB'; END 

'A EQUALS AB' printed ... Could you tell me why?

Reading this page really doesn't help ...

thanks.

+4
source share
2 answers

Since you declare nvarchar variables without a given length, they default to a length of 1. Therefore, both variables contain only the first character 'A' .

Try this instead:

 DECLARE @A NVARCHAR(10) = 'A'; DECLARE @AB NVARCHAR(10) = 'AB'; if @A = @AB BEGIN PRINT N'A EQUALS AB'; END 
+7
source
 DECLARE @A NVARCHAR = 'A'; -- IS a NVARCHAR(1) containg 'A' DECLARE @AB NVARCHAR = 'AB'; -- IS also a NVARCHAR(1) containg 'A' DECLARE @AB2 NVARCHAR(2) = 'AB'; -- IS a NVARCHAR(2) containg 'AB' if @A = @AB BEGIN PRINT N'A EQUALS AB'; END if @A != @AB2 BEGIN PRINT N'A NOT EQUALS AB'; END 
+2
source

Source: https://habr.com/ru/post/1397037/


All Articles