Why should you always write "varchar" with the length in brackets behind it? Often, you get the right outcome without doing so
-1
votes
2
answers
721
views
"Often, you get the right outcome without doing so."
Example:
select CONVERT(varchar, getdate(), 112)
outputs
20240417
I saw this in quite a few places on Stack Exchange until I found a tiny remark that told the reader not to forget the length in brackets. I claimed that this is not needed if you set the style number for a datetime like this. Yet, I got enough insight now to understand that "varchar should never stand alone", it should always be written as something like
varchar(1234)
.
As for the code above, that would be:
select CONVERT(varchar(8), getdate(), 112)
If you look at it, the output is the same:
20240417
Why should you still always write varchar with the length in brackets behind it?
#### PS: If you can, take even char(8) instead of varchar(8) / nvarchar(8)
A remark below went even further: char(8)
should be taken since:
> no value in style 112 will ever be less than 8 characters.
#### Links that bring up this question
This is just a random list of some links where I saw varchar() without brackets. There are many more out there.
- [Convert date yyyy-mm-dd to integer YYYYMM - DBA SE](https://dba.stackexchange.com/a/106900/212659)
- [SQL Server Convert Varchar to Datetime - Stack Overflow](https://stackoverflow.com/a/10247180/11154841)
- [Convert date to number data type - Stack Overflow](https://stackoverflow.com/a/63625407/11154841)
- [How to get a date in YYYY-MM-DD format from a TSQL datetime field?](https://stackoverflow.com/q/889629/11154841)
- [Convert date to YYYYMM format](https://stackoverflow.com/a/14217859/11154841)
- [SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value](https://stackoverflow.com/a/20840132/11154841)
Asked by questionto42
(366 rep)
Apr 17, 2024, 04:36 PM
Last activity: Jun 11, 2024, 06:56 PM
Last activity: Jun 11, 2024, 06:56 PM