0

I am using VBA to upload data from and Excel file into SQL Server. The date column in the CSV as I get is in the "mm/dd/yy format". How do I format the date to be in the SQL Server format "YYYY-MM-DD hh:mm:ss:000" before I pass it to the query to insert the record?

I declare the variable

Dim InvoiceDate As Date

I get the value from the workbook

InvoiceDate = row.Cells(5).Value

I insert into the table

INSERT INTO table(InvoiceDate) VALUES (" & InvoiceDate & ")

I end up with this:

1900-01-01 00:00:00.000
7
  • Perhaps using Format$. Commented Nov 10, 2020 at 18:57
  • Why write your own script in VBA if there is an Import and Export Wizard that is fully documented and supports Microsoft Excel? Commented Nov 10, 2020 at 18:58
  • 1
    @BigBen is correct - Format$(InvoiceDate,"YYYY-MM-DD hh:mm:ss:000") will do it. Commented Nov 10, 2020 at 19:04
  • 1
    SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection - check out Little Bobby Tables Commented Nov 10, 2020 at 19:34
  • @ScottHoltzman is correct but I suspect the InvoiceDate in the code is assigned the value of an empty cell! Commented Nov 10, 2020 at 19:48

1 Answer 1

1

So I added my own variable after getting the value from the Excel worksheet and before uploading to SQL: sDate = Format(InvoiceDate, "YYYY-MM-DD hh:mm:ss:000")

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

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.