Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In SQL, how do I convert a date field into a string if null?

I would like to write an SQL query in SQL Server 2008 R2 that converts a date to a string when it is NULL. For example...

    Date                            ShipmentRef     RecieptNo
    2009-01-01 03:12:11.596         DS298-YYY       18060
                                    FM298-YYY       95464
    2010-11-11 08:33:55.974         IL298-YYY       56703
    2003-08-01 07:00:44.846         UI835-XYX       40264
                                    US655-YXY       34643
    2004-03-07 12:46:33.352         WE242-XXX       83755

The above data is just a sample table of what my current data looks like. When I run the SELECT query, I want it to return the data as follows:

    Date                            ShipmentRef     RecieptNo
    2009-01-01 03:12:11.596         DS298-YYY       18060
    InsertRandomStringHere          FM298-YYY       95464
    2010-11-11 08:33:55.974         IL298-YYY       56703
    2003-08-01 07:00:44.846         UI835-XYX       40264
    InsertRandomStringHere          US655-YXY       34643
    2004-03-07 12:46:33.352         WE242-XXX       83755

I'm not sure which would be better, CASE or CONVERT. Any help you give me will be very much appreciated.

like image 417
Miss M Avatar asked Dec 11 '22 19:12

Miss M


1 Answers

Assuming SQL-Server:

SELECT ISNULL(CONVERT(nVarChar(30), Date, 121), 'InsertRandomStringHere') 

DEMO

CAST and CONVERT (Transact-SQL)

like image 79
Tim Schmelter Avatar answered Dec 14 '22 08:12

Tim Schmelter