2

Why the output is different of this query

SELECT DATALENGTH(CAST('test' AS VARCHAR)), DATALENGTH(CAST('test' AS CHAR))

outPut:

4,30

Bridge
  • 29,818
  • 9
  • 60
  • 82
Jeevan Bhatt
  • 5,881
  • 18
  • 54
  • 82

2 Answers2

5

VarChar always adjusts to the length of the string passed. hence the output is 4.

CHAR has default length of 30 and hence the output is 30.

Sachin Shanbhag
  • 54,530
  • 11
  • 89
  • 103
1

Because "When n is not specified when using the CAST and CONVERT functions, the default length is 30". But when DataLength is applied to a varchar field, it ignores trailing spaces, while for a char field the length is just the size of the field itself.

MartW
  • 12,348
  • 3
  • 44
  • 68