"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
- SQL Server Convert Varchar to Datetime - Stack Overflow
- Convert date to number data type - Stack Overflow
- How to get a date in YYYY-MM-DD format from a TSQL datetime field?
- Convert date to YYYYMM format
- SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value