3

Is there any issue with the following SQL? Here no length has been used while converting to varchar.

SELECT CAST('abc' AS varchar)

Should I use

 SELECT CAST('abc' AS varchar(3))
OzrenTkalcecKrznaric
  • 5,535
  • 4
  • 34
  • 57
user1672097
  • 361
  • 1
  • 4
  • 12
  • 1
    you should **NEVER** use just `varchar`, always specify a length. Besides being just lazy, you should always size fields properly, it is just one of the ways the database protects the data's integrity. – KM. Jul 23 '13 at 17:57

3 Answers3

4

If you do not specify varchar(n) then n will be assumed to be 30. For example: If we run the query below, we get 30 chars of output.

CAST('01234567890123456789012345678901234567890123456789012345678901234567890123456789' as varchar) 

Also have a look at the following msdn article for more clarity.

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Mangoose
  • 922
  • 1
  • 9
  • 17
1

As long as your string does not exceed 30 characters, you're fine.
SQL Server will try to cast to the default length which is 30 characters.

If you try to cast a string that exceeds this length, your string will be truncated to 30 characters.

Example:

DECLARE @Example VARCHAR(35) = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' -- 35 Characters
SELECT LEN(cast(@Example as varchar)) AS [Result]

Result
30
Khan
  • 17,904
  • 5
  • 47
  • 59
0

If you will use the cast to insert the data to a column that has a fixed length the second statement will help you avoid the "string or binary data would be truncated" error by truncating the data

SQLException : String or binary data would be truncated

Community
  • 1
  • 1
asafrob
  • 1,838
  • 13
  • 16