Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NVarChar Variable Comparison

this is maybe really stupid. I don't really understand NVarChar comparison in T-SQL.. if i try something like that :

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

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

Reading this page does not really help...

thanks.

like image 787
LB40 Avatar asked Feb 17 '12 14:02

LB40


2 Answers

Because you are declaring your nvarchar variables with no length specified, they are defaulting to a length of 1. Hence both variables only contain 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
like image 83
Joe Stefanelli Avatar answered Oct 11 '22 09:10

Joe Stefanelli


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
like image 38
Mithrandir Avatar answered Oct 11 '22 10:10

Mithrandir