2

I'm trying to do a comparison of data between 2 tables, where I need to join multiple columns as a composite key to get a unique identifier. I'm using a CTE and the code I have is:

WITH SuburbDataTest AS (
  SELECT *
    ,  CAST(Address AS NVARCHAR(100))+' ' +CAST(LivingAddress AS NVARCHAR(2))
    + ' ' + CAST(StartDate AS NVARCHAR(11))+ ' ' +CAST(AddressTypeId AS NVARCHAR(1))
    + ' ' +CAST(SuburbId AS NVARCHAR(1))AS SuburbDataTestColumn
  FROM [mig].[ConsumerAddressMigration]
  WHERE SuburbId is NOT NULL
)
SELECT *
FROM SuburbDataTest staging
WHERE SuburbDataTestColumn IN (
  SELECT Address+' ' +CAST(LivingAddress AS NVARCHAR(2))+ ' '+CAST(StartDate AS NVARCHAR(11))
    + ' ' +CAST(AddressTypeId AS NVARCHAR(1))+ ' ' +CAST(SuburbId AS NVARCHAR(1)) AS SuburbDataTestColumn
  FROM [dbo].[tblConsumerAddress]
)

Unfortunately I'm getting

Arithmetic overflow error converting expression to data type nvarchar.

Any ideas?

1
  • can we see the schema of [mig].[ConsumerAddressMigration] and that of [dbo].[tblConsumerAddress]? Commented Feb 21, 2020 at 0:47

1 Answer 1

3

This happens when you are converting a number to a string -- and the string is not big enough. I would guess this is the problem:

CAST(SuburbId AS NVARCHAR(1))

If SuburbId is a number larger than 9, then this will generate an error. Or, for that matter if the value is negative you'll get the same error as well.

Sign up to request clarification or add additional context in comments.

1 Comment

Duh! I was so blind! Really grateful @Gordon Linoff!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.