1

I have the following tables with column/row values:

tbl1
ID
1
2
3

tbl2
ID    Color    DateRegister
1     'Red'     '2021-02-04 00:00:00.000'
3     'Blue'    '2021-02-04 00:00:00.000'

I'm trying to write a SQL code that selects records from tbl1 with tbl2 via LEFT JOIN. If there is no connected records between tbl1 and tbl2, the tbl2 columns should be NULL. I use CASE to display blank strings for the NULL values. This does not work for the date column.

SELECT
tbl1.ID
, CASE WHEN tbl2.Color IS NULL THEN ''  ELSE tbl2.Color END AS 'Batch-Color'
, tbl2.DateRegister as 'Date-1'
, CASE WHEN tbl2.DateRegister IS NULL  THEN '' ELSE WHEN tbl2.DateRegister END AS 'Batch-Date'
FROM tbl1 LEFT JOIN tbl2 ON tbl1.ID = tbl2.ID

Here is the output. I need the date to display as a blank string instead of '1900-01-01'

ID    Batch-Color    Date-1                      Batch-Date
1     'Red'          '2021-05-28 00:00:00.000'   '2021-05-28 00:00:00.000'
2     ''             NULL                        '1900-01-01 00:00:00.000'
3     'Blue'         '2021-02-04 00:00:00.000'   '2021-02-04 00:00:00.000'
2
  • 1
    The best approach is to simply keep the NULL values, and let your client code format it as what it wants. If you convert to blanks, you also have to decide what format to use to convert the dates that are not NULL -- relying on what the server implicitly produces based on regional settings is a bad idea. Commented May 29, 2021 at 8:38
  • Can't agree more with the above comment. '' is by definition not a date and you can't store or resolve non-date values in a date and time column in SQL; a column must be a single strongly typed data type. Leave it to your presentation layer to display NULL as a blank value, not the RDBMS. Commented May 29, 2021 at 8:56

2 Answers 2

2

You must convert DateRegister to VARCHAR with style = 121 (to preserve the format that you want).
Also, instead of the CASE expressions, it's simpler with COALESCE():

SELECT tbl1.ID, 
       COALESCE(tbl2.Color, '') AS [Batch-Color],
       tbl2.DateRegister AS [Date-1],
       COALESCE(CONVERT(VARCHAR(23), tbl2.DateRegister, 121), '') AS [Batch-Date]
FROM tbl1 LEFT JOIN tbl2 
ON tbl1.ID = tbl2.ID

See the demo.

Sign up to request clarification or add additional context in comments.

3 Comments

Using VARCHAR without a length is a bad habit to kick.
@JeroenMostert yes, I had to count, it's 23 max.
This worked for me. I got the results I needed. Much obliged. :-)
0

You need to cast your date to a varchar, otherwise the blank string is being implicitely cast to date hence your 1900-01-01.

Try this pattern:

select... coalesce(convert(varchar(25),[Batch-Date]),'')...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.