LB40
LB40

Reputation: 12341

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.

Upvotes: 5

Views: 6809

Answers (2)

Mithrandir
Mithrandir

Reputation: 25387

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

Upvotes: 2

Joe Stefanelli
Joe Stefanelli

Reputation: 135858

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

Upvotes: 8

Related Questions