Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

sql - What is the effect of omitting size in nvarchar declaration

I usually define size when declaring parameters in my SP, like :

@myParam nvarchar(size)

or when I casting or converting:

CAST(@myParam AS nvarchar(size))

Recently I've removed size from my CAST functions like:

CAST(@myParam AS nvarchar)

and I'm bit worried if that is going to come and bite me when least expected :-(, since I noticed truncation on nvarchar variables when using recursive CTE and casting nvarchar without specifying size.

Any comments?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you omit the size, it defaults to 30. See this:

http://msdn.microsoft.com/en-us/library/ms186939.aspx

To see this in action, try executing the following statements:

--outputs: 12345678901234567890.098765432 
select cast (12345678901234567890.098765432 as nvarchar)

--throws "Arithmetic overflow error converting expression to data type nvarchar."
select cast (12345678901234567890.0987654321 as nvarchar) 

--outputs: 12345678901234567890.0987654321 
select cast (12345678901234567890.0987654321 as nvarchar(31))

Per @krul's comment; 30 is the default length for CAST; however the default length for a data definition or variable declaration is 1.

NB: There's also an STR function which converts numeric fields to strings, for which the default length is 10.

--outputs: 1234567890
select str(1234567890)

--outputs: **********
select str(12345678901)

--outputs: 12345678901
select str(12345678901,11)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...