2

I have a query where I'm trying to concatenate a GUID to a string. No matter what I do, or what I try to convert the GUID to, I get an arithmetic overflow error. Even this:

select CAST(NEWID() as nvarchar)

Returns:

Msg 8115, Level 16, State 2, Line 1 Arithmetic overflow error converting expression to data type nvarchar

All similar questions have been resolved by a CAST or CONVERT but this always returns an error. Same result for CHAR or VARCHAR. Is there a setting I have to change to make this work or something?

1 Answer 1

4

You've fallen into the trap of not specifying a length for your nvarchar. What you want is:

select CAST(NEWID() as nvarchar(36))

[ GUIDs are rendered as 36 character strings ]

When length is unspecified, SQL Server uses a default length of 30 for varchar/nvarchar when used in CAST and CONVERT functions.

You should ALWAYS explicitly specify your string length.

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

1 Comment

This was very valuable info, thanks. I always assumed not specifying the length in a CONVERT or CAST would just mean 'use whichever length works'.

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.