Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate a string and GETDATE() in MSSQL

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?

like image 832
Kjartan Avatar asked Aug 09 '11 08:08

Kjartan


2 Answers

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
like image 133
Damith Avatar answered Sep 30 '22 00:09

Damith


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.

like image 36
Bernhard Kircher Avatar answered Sep 30 '22 00:09

Bernhard Kircher