Rodrigo
Rodrigo

Reputation: 19

Convert string to date SQL Server

I have a query when I need to convert a string to datetime, I use

CONVERT(DATETIME, '')

but it's still not working. My column fechac is of type Datetime.

If I pass in for example '2019-11-20 00:03:56.120', the query works but I don't need the time because is a parameter from an application web and I send the date example '2019-11-20'. Thanks!

This is my query:

SELECT * 
FROM table 
WHERE cb.fechac = CONVERT(DATETIME, '2019-11-20');

Upvotes: 0

Views: 813

Answers (3)

Thom A
Thom A

Reputation: 95554

Use the format yyyyMMdd. With the datetime datatype yyyy-MM-dd is ambiguous. Otherwise, use a style code:

CONVERT(datetime,'2019-11-20',126);
CONVERT(datetime,'20191120')

Reading a lot through the lines in the comments here, however, are you actually after..?:

WHERE fechac >= '20191120'
  AND fechac < '20191121'

Final reading through the lines. it appears the OP is actuaklly passing a parameter (I assume of the data type date), therefore...

WHERE fechac >= @fechac
  AND fechac < DATEADD(DAY, 1, @fechac)

Upvotes: 2

dougp
dougp

Reputation: 3089

SELECT *
FROM table cb
WHERE cast(cb.fechac as date) = convert(date, '2019-11-20', 23)

Upvotes: -1

Gordon Linoff
Gordon Linoff

Reputation: 1269483

This should work on any system, regardless of internationalization settings:

WHERE cb.fechac=convert(DATE,'20191120');

Upvotes: 0

Related Questions