8

I need to insert a string (a comment) which should include a date. What I need is basically the following simple operation:

INSERT INTO [Table_1]
           ([textColumn])
     VALUES
           ('Date: ' + GETDATE())
GO

This however, returns the following error: Conversion failed when converting date and/or time from character string.

Any quick fixes?

Kjartan
  • 18,591
  • 15
  • 71
  • 96

4 Answers4

14

what is the date time format you need?

select one from here http://www.sql-server-helper.com/tips/date-formats.aspx and convert it to a char as bellow

INSERT INTO [Table_1]
           ([textColumn])
     VALUES
           ('Date: ' +CONVERT(CHAR(10),  GETDATE(), 120))
GO
Damith
  • 62,401
  • 13
  • 102
  • 153
  • Thanks, that was just what I needed. I ended up with this version: `convert(VARCHAR(11), GETDATE(), 106)) -- Format: 09 Aug 2011` – Kjartan Aug 09 '11 at 08:12
5

Depending on the column's definition, you can try to cast or convert the date to the desired type:

INSERT INTO [Table_1]
       ([textColumn])
 VALUES
       ('Date: ' + CAST(GETDATE() as nvarchar(max)))
GO

To format the date, use Convert, e.g.

 INSERT INTO [Table_1]
       ([textColumn])
 VALUES
       ('Date: ' + convert(nvarchar(max), GETDATE(), 101))
 GO

The last Parameter defines the format - see msdn for details.

Bernhard Kircher
  • 4,132
  • 3
  • 32
  • 38
1

Instead of adding it as part of data, you can store only datetime in column append the text Date using SELECT statement

select 'Date '+ CAST(GETDATE() as nvarchar(max)) from [Table_1]

Madhivanan
  • 13,470
  • 1
  • 24
  • 29
0

In case one of output field is null, the combined output will be null. To solve, try this

lname + ',' + space(1) + fname + space(1) + (case when mname is null then '' else mname end) as FullName

from: http://forums.devshed.com/ms-sql-development-95/concatenate-when-one-column-is-null-371723.html

I tried and it works!

Roman C
  • 49,761
  • 33
  • 66
  • 176