Convert sql dates to excel

The problem: I would like to convert datetime of SQL Server into Excel datetime format.

Example 1: from 2018-08-23 15:32:32.000 to 43335,65

Example 2: from 1985-03-26 10:35:42.000 to 31132,44

What I have tried: inspired by this answer, I tried this query

SELECT DATEDIFF(day, @MyDatetime, GETDATE())

which works if you want to convert a date (without the hours), but how to convert the time too?

In Excel, the time is saved in the decimal part of the number so I’ve tried to use

SELECT DATEDIFF(SECOND, '1899/12/30 00:00:00.000', GETDATE())

but this results in an overflow error.

The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.

  • Remove From My Forums
  • Вопрос

  • Hi all,

    I want to convert SQL datetime to Excel datetime.

    «2012-07-04 07:21:41.840»

    Thanks

Ответы

  • Hi Sai.N,

    As far as I know, when exporting datetime value from SQL Server to Excel, the Excel date format will be affected by country/region where you are located, if we need a special date format with Excel, I think we need to format the data with Excel. With your
    requirement, please format the data as Number, Decimal place as 5. I listed some documents about format date value with Excel, you can refer to them.

    Format date with Excel:
    http://spreadsheets.about.com/od/excelformatting/ss/number_format_5.htm

    Change the default date, time, number or measurement format:
    http://office.microsoft.com/en-us/excel-help/change-the-default-date-time-number-or-measurement-format-HA010351415.aspx


    Allen Li
    TechNet Community Support

    • Предложено в качестве ответа

      11 апреля 2013 г. 4:47

    • Помечено в качестве ответа
      Allen Li — MSFT
      12 апреля 2013 г. 9:30

How do I convert SQL date to excel?

So, if you’re just looking for dates, you can perform the following:

  1. Copy range from SQL Server Management Studio.
  2. Paste into Excel.
  3. Select the range of cells that you need formatted as Dates.
  4. Press Ctrl + Shift + 3.

Is date of birth necessary in CV?

Date of birth You may include your birth date if you wish. However, it is no longer necessary since the Employment Equality Acts made age discrimination illegal in the recruitment process. If you’re having issues getting interviews, try removing it from your CV to see if it has a positive impact.

Is DOB mandatory for resume?

Age or date of birth, gender, nationality, and marital status should all be left off of your resume for similar reasons of non-discrimination. It is not necessary to include your full address in your resume – your city and state is sufficient.

Should you include all jobs on CV?

There is no obligation to include every detail of your life on a CV. Plus, you can remove a job from your CV if it enables you to sell yourself better to an employer.

What employers look for in a CV?

What employers and recruiters look for in a CV

  • Roles and responsibilities.
  • Experience.
  • Skills.
  • Results and achievements.
  • Education.
  • Easy to read.
  • No inconsistencies.
  • Relevant language.

How do I get my CV selected?

  1. Make sure you meet the qualifications. Qualifications for being considered for a job are usually listed at the bottom of the job ad.
  2. Customize your resume.
  3. Focus on your accomplishments.
  4. Include your most relevant skills.
  5. Add a cover letter.
  6. Use a connection.
  7. Use a basic font.
  8. Add a skills section.

How do I know if my CV is good?

A CV should be two pages, a maximum of three. Make use of bullet points and write in short sharp sentences. Don’t waffle. Focus on job content i.e. what you did….Is it brief and clear?

  1. Name.
  2. Current title/company.
  3. Previous title/company.
  4. Current title/company start/end dates.
  5. Previous title/company start/end dates.

How can a 16 year old write a CV?

Here’s how to write a CV for a 16-year-old:

  1. Use the Best Format for Your CV for a 16-Year-Old.
  2. Put Your Contact Details in Your CV Header.
  3. Write a Personal Statement for a 16-Year-Old CV.
  4. Include an Education Section.
  5. Complete Your Work Experience Section (If You Have Any)
  6. Show Off Your CV for a 16-Year-Old Skills.

Let’s start with a simple query

SELECT TOP 10 Invoice, InvoiceDate FROM dbo.OSASGrossMargin_vw WHERE GLYear = 2016

It returns 10 rows containing an invoice number and an invoice date. When I hover over InvoiceDate, you can see its data type is date. What you can’t see, but trust me it’s there, is that Invoice is a varchar(50) (that’s a String in VBA parlance).

Copy and Paste

Once I run the query in SSMS, I can F6 down to the Query Grid, Ctrl+A to select everything, and Ctrl+C to copy it (Ctrl+Shift+C to copy the headers too). Then over to Excel where a Ctrl+V finishes the job.

That’s pretty good except for one problem. My string invoice numbers were converted to numbers. I can tell because they’re right-aligned. That’s not a particular problem here because they didn’t happen to have any leading zeros. But if they had, the leading zeros would have been lost.

I could have formatted the column for Text before I pasted.

Those little green triangles means everything is right with the world. My invoice numbers are text and my dates are dates. Percentage of the time I will remember to format the column before I paste: 0%.

External Data Query

If I want my varchars to remain varchars then one option is to use an External Data Query in Excel.

My invoice numbers look good and there’s no green triangles. But something is not quite right with those dates. I’m sure you noticed. I’ll get back to that in a minute. But first, here’s how you create an External Data Query.

Data Get External Data From Other Sources From SQL Server

Follow the wizard by first connecting to the server.

If you’re using SQL Server Express, you can use the command line to find the names of local servers: sqlcmd -L (that’s a capital L).

I have no idea what that is as I don’t have SQL Server Express on my machine. If you’re using regular old SQL Server then ask your DBA what the server name is. If you are the DBA, then you’re in trouble.

Next I tell it what database I want to use. In this case, I uncheck Connect to a specific table because I want to write a query.

On the last screen, I change the Friendly Name

In the next step, I select which table I want to use. In a previous step, we said don’t connect to a specific table. There are at least two kinds of OLEDB connections to SQL Server data: Table and SQL. If you check the box to connect to a specific table, it creates a Table connection and you get the whole table. If you uncheck the box, you get to pick the table and write a query, as we’ll see in a moment. For my purposes, I’m selected the view I used in the SQL statement at the start of this post.

On the Import Data dialog, you can just hit OK and bring in the whole table. But if you we’re going to do that, you might as well have checked the box a couple of steps ago. Because I want to write a query, I’m going to select Properties here.

On the Definition tab, I change the Command Type from Table to SQL and put my query in the Command Text box.

Click through the rest and you’re home. Wow, that’s a lot of work.

Automating External Data

Most of the queries I want come from one database. So I created this little gem to get me started

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

Public Sub CreateSQLTable()

    Dim lo As ListObject

    Dim qt As QueryTable

    Dim aCon(1 To 5) As String

    aCon(1) = «OLEDB;Provider=SQLOLEDB.1;»

    aCon(2) = «Integrated Security=SSPI;Persist Security Info=True;Data Source=MyDBServer;»

    aCon(3) = «Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;»

    aCon(4) = «Workstation ID=MyWorkstation;Use Encryption for Data=False;»

    aCon(5) = «Tag with column collation when possible=False;Initial Catalog=OSAS Reporting»

    If ActiveSheet.UsedRange.Address = «$A$1» Then

        Set lo = ActiveSheet.ListObjects.Add(xlSrcExternal, Join(aCon, vbNullString), , , ActiveSheet.Range(«$A$1»))

        Set qt = lo.QueryTable

        qt.CommandType = xlCmdSql

        qt.CommandText = «SELECT 1»

        qt.PreserveColumnInfo = False

        qt.Refresh BackgroundQuery:=False

    End If

End Sub

This puts a one column, one row External Data query into cell A1 that’s already connected to my favorite database.

I write my query in SSMS, copy the SQL statement, and head over to Excel. From a cell within the External Data Query range, I press Alt+D+D+E to get the Edit OLE DB Query box. From here I can change my Initial Catalog in the Connection in case I’m using a different database and I can paste my SQL statement into Command Text.

That’s-a nice-a doughnut.

Stupid Dates

Using an External Data Query, we solved our strings-that-look-like-numbers conversion problem, but introduced another problem. My dates no longer look like dates. They’re all left justified and weirdly formatted. Also, those strings-that-look-like-dates are pretty tenuous. If you F2 and Enter, you convert them to numbers. So if you’re making something permanent (as opposed to some quick and dirty analysis), you still want to format the column as Text.

The problem with the dates is that SQL Server uses one kind of data format and Excel uses a different, incompatible type. Basically Excel doesn’t know it’s a date. If you copy and paste, the trip through the clipboard forces Excel to analyze the data to determine it’s data type (that’s why my varchars turn to numbers), so the dates get converted because at least they look like dates. But through OLEDB, not so much. The data types stay true throughout the process. Hooray for varchars, too bad for dates.

SQL Server has a ton of date formats (well, five actually). The SMALLDATETIME is a pretty snazzy data type that just so happens to work in Excel.

Oh, if you’ve ever tried to convert an Access database to SQL Server, this date business is old news to you. Just know that you are not alone. Others are hurting too.

I’m not going to dumb down my SQL data types just for Excel. But I am willing to convert.

SELECT TOP 10

        Invoice

      , CONVERT(SMALLDATETIME, InvoiceDate) InvoiceDate

FROM    dbo.OSASGrossMargin_vw

WHERE   GLYear = 2016

When I put that into Excel, my dates are dates.

Well, almost. They still need a little formatting love. Now all you have to do is remember to convert all your dates before you bring them over. The good news is that if you forget, you can simply edit the SQL to add the CONVERT function. If you have RedGate SQLPrompt, there’s even better news. I created this snippet.

You select your date field, press and release Ctrl, type xld (that stands for Excel Date) and it converts

to

      , CONVERT(SMALLDATETIME,InvoiceDate) InvoiceDate

SQL Prompt

I don’t know how much SQL Prompt costs because my employer pays for it. But I can’t imagine working in SSMS without it. In a recent update, they added a new right-click menu item to the Query Grid right-click menu: Open in Excel

As you might have guessed, this is the best of both worlds. You get varchars and dates acting as they should. You still need a little date formatting.

And that’s everything you ever wanted to know about getting data from SSMS to Excel. And then some.

I’ve already asked the question at: StackOverFlow and got sent to this place here.

I’m importing dates from a German SQL Server table into a German Excel file via the built-in Excel connection tool.

However the date format is just like in the SQL Server: 2012-08-08 but I want to display: 08.08.2012. When I double-click inside a cell it will recognize the German date formatting but of course I would like to have that format for the entire column in the beginning without having to manually change it.

I also need to be able to use these dates for calculations.

I know there is a text box where you can enter a SQL «Definition» in the Excel Connection tool but it doesn’t really work with «normal» SQL-statements.

Do I need to change something in SQL Server or how do I make this work?

Community's user avatar

asked Aug 8, 2012 at 12:00

TonyC's user avatar

5

If I understand you correctly, you’re saying the field in SQL Server is stored in datetime format, and you want to pull that info into Excel by creating a connection to your SQL Server table, and display it in German date form dd.mm.yyyy

You shouldn’t need to edit the SQL in the definition tab of the Connection Properties window for formatting purposes — this may be simpler than you think.

  1. Use Excel’s Data Connection Wizard to pull in the table you want to show in Excel.

  2. Then in Excel, for each date column, select the entire column, click format cells (or the handy keyboard shortcut is Ctrl+1), then on the Number tab click Custom at the bottom of the column on the left. In the «Type» text box, enter: dd.mm.yyyy

  3. The next time you refresh the data, Excel should retain the German formatting of your dates. You can use anything in these columns for calculations, Excel knows they are dates.

answered Jan 17, 2013 at 11:47

Andi Mohr's user avatar

Andi MohrAndi Mohr

4,1704 gold badges31 silver badges46 bronze badges

  • If you would like to post, please check out the MrExcel Message Board FAQ and register here. If you forgot your password, you can reset your password.

  • Thread starter

    dlorenc

  • Start date

    Mar 2, 2009

  • #1

Im confused..how do I convert a number that was imported from ms sql 2005…into its date format in excel?..

this sql statement: select actual_end_date,dateadd(s,Actual_End_Date,’19700101′)

gives me:
actual_end_date (No column name)
1203693715 2008-02-22 15:21:55.000.

now I have: 1203693715, in an excel cell..and I know it should convert to 2/22/08…???…

Last edited: Mar 2, 2009

Add Bullets to Range

Select range. Press Ctrl+1. On Number tab, choose Custom. Type Alt+7 then space then @ sign (using 7 on numeric keypad)

  • #2

boy was I confused…my formula was pointing to the wrong cell..*sigh*..here is my solution..

F8 = 1,203,693,715.0 # seconds from 1/1/1970

as excel dates work in days, the conversion is =+E13+(F8/(60*60*24))

where e13 is 1/1/1970 (or use the raw number (set to general instead of date): 25569
and F8 is my number of seconds…

result is 2/22/08 3:21 PM

Threads
1,192,533
Messages
5,993,039
Members
440,466
Latest member
QuinnE

In several scenarios, we need to use some data which is available in SQL Server, but we need it in MS Excel. Instead of putting every data manually into Excel, the SQL Server provides an option to import and export data from SQL Server to Excel sheets. In this tutorial, we will learn various methods of importing and exporting data from or to SQL Server. Also, we will cover these topics.

  • How to export data from SQL Server to Excel using Import and Export Wizard
  • How to export data from SQL Server to Excel automatically
  • How to export data from SQL Server to Excel using the query
  • How to import data from SQL Server into Excel using Data Connection Wizard
  • Export data from SQL Server to Excel using stored procedures

Here, for all the functionality, I have used SQL Server 2019 Express edition.

Export data from SQL Server to Excel using Import and Export Wizard

In this section, we will learn how to export data from the SQL Server database into an Excel worksheet automatically using import & export Wizard. We will be using the import and export wizard in SQL Server Management Studio.

  • Below is the table that we are going to export automatically using the import and export wizard in SQL Server.
export data from SQL Server to Excel using Import and Export Wizard
Data to be Imported
  • Right-click on the database using which table is created.
  • Select the Tasks option from the dropdown another dropdown will appear.
  • Click on the Export Data.
Import to Excel Wizard in sql server
Running the Import and Export Wizard
  • Once you have clicked on the Export Data option from the drop-down menu then Import and Export wizard window will appear.
  • Click on Next to proceed in the process.
Export data from SQL Server to Excel
Import and Export Wizard
  • Once you have clicked on the Next button on Import and Export wizard a new window will appear asking to Choose a Data Source
  • Select SQL Server Native Client 11.0 in Data Source
  • Select the instance from the dropdown for the Server name.
  • For Authentication, you can use:
    • Use Windows Authentication, which means the username and password of your computer. It automatically picks up from the system.
    • Use SQL Server Authentication, this requests the Username and Password that was creating an instance.
  • Select the database name from the dropdown and click on the Next button.
export data from SQL Server to Excel using Import and Export Wizard
Data Source
  • The SQL Server Import and Export Wizard will ask for destination details. Choose Destination field as Microsoft Excel
  • Give the path to the Excel file into which you want to export the data
  • Select the Excel Version according to the version of the Excel that you have installed on your system and click Next.
How to export data from SQL Server to Excel using Import and Export Wizard
Data Destination
  • Now the SQL Server Import and Export Wizard will ask whether you want to copy all data from the existing tables or query-specific data. We can select Copy data from one or more tables or views to import all the table data.
  • We will also explain how you can copy data that is modified by SQL query with Write a query to specify the data to transfer option

Read: How to Create a Database in SQL Server 2019 [Step by Step]

Export data from SQL Server to Excel automatically

SQL Server 2019 provides a method to export all the data from SQL server to Excel worksheet. In this section, we will demonstrate how to export SQL server data to Excel automatically using Import and Export Wizard.

Import to SQL specify table copy
Specify type of Operation
  • Choose the table from the Source tab which you want to export and specify the name of the table in the Destination tab and click Next
How to export data from SQL Server to Excel
Select Table
  • In the next step, you can choose whether you want to save the SSIS Package or not. In this section, we will continue without saving.
How to export data from SQL Server 2019 to Excel
Run Package
  • Now you will see the final overview of the operation before the execution, click on the Finish Button.
How to export data from SQL Server to Excel automatically
Final Overview
  • Now data has been successfully exported from SQL Server to Excel worksheet.Click on the Close button to exit the window.
How to export data from SQL Server to Excel
Process Completed
  • You can check that the file is created at the specified location.
How to export data from SQL Server to Excel automatically
Exported Data Successfully

Read: How to create a table in sql server management studio

At times, it is not necessary to export all the table data. Instead, we need to export data using a query. In such situations, we can export query-specific data from SQL Server to Excel worksheet.

  • After selecting the source and destination of data using SQL Import and Export Wizard, the wizard show two options. Choose the second option which says Write a query to specify the data to transfer and then click on the Next button.
export data from SQL Server to Excel using query
Export Using Query
  • Then we need to specify the query which we want to implement. In our case we will execute a query to show the Name and Age of people whose salaries are greater than 100000. After writing the query, click Next
export data from SQL Server 2019 to Excel using query
Writing the Query
  • Now you will see the overview of table source and destination. You can also see how the data looks after the query is implemented by clicking on the Preview button. Then click Next
export data from SQL Server 2017 to Excel using query
Data Preview
  • Run immediately is checked by default, click on Next button.
How to export data from SQL Server to Excel using query
Save and Run Package Windows
  • Now all the configurations are complete. You can click on the Finish button to start the Wizard
How to export data from SQL Server to Excel using query
Complete the Wizard
  • If all actions are successfully completed, your query is implemented and the data is exported. You can close this window.
Import from SQL to Excel Execution success
Success
  • Navigate to the destination path and you can see that data is exported successfully
How to export data from SQL Server to Excel using query
Exported Data

Read: Advanced Stored Procedure Examples in SQL Server

How to import data from SQL Server into Excel using Data Connection Wizard

We can also import data from SQL Server to Excel using the Data Connection Wizard in Excel. The benefit of using this method is that we can get live data from SQL Server.

Live data means that the changes made in the SQL Server database will be reflected into the Excel worksheet also. We will demonstrate this with the help of an example

  • Open MS Excel and create a new worksheet or open an existing worksheet into which you want to import the data from SQL Server
  • Go to the Data tab and click on From Other Sources and then From SQL Server as shown in the image below
import data from SQL Server into Excel
Create Connection to SQL Server
  • Enter the name of the Server instance that you have created in the Server name field. You can use either Windows Authentication or SQL Server login credentials to make a connection with the database. After inserting the required details, click Next
import data from SQL Server 2019 into Excel
Data Connection Wizard
  • Now select the database and the table that you want to import. You can also import data from multiple tables by checking the option Enable selection of multiple tables
How to import data from SQL Server into Excel
Select Database and Table
  • Save the Data Connection File. Add description to it to store more information about the connection. It will help you to know the information about the connection when you will connect to the database again. Click Next
How to import data from SQL Server 2019 into Excel
Save Connection
  • A small window will appear where you can decide how you want to view your data in the Excel Workbook. You can import the data either in an existing worksheet or in a new worksheet. Select the desired option and then click OK
How to import data from SQL Server 2017 into Excel
Format Data
  • Now you can see, your data is imported successfully from SQL Server
How to import data from SQL Server into Excel
Imported Data
  • As mentioned above, this type of connection is a live connection to the database. Try to change the data in SQL Server. You will see that the changes will be reflected in the Excel worksheet also. Let us see an example
  • Run the following query in the SQL Query Window in SQL Studio Management
update Employees set Age =20 where [Employee ID]=1;
select * from Employees;

Here is the implementation of above mentioned code snippet.

import to excel updated data studio
Result after Query
  • Changes are made in the table. Now refresh the excel worksheet where you have imported the data or open it again. You will the same changes in the imported data
how to import data from SQL Server into MS Excel
Updated Data

In this tutorial, we have learned how to import data from SQL Server into MS Excel using Import and Export wizard in different ways. Also, we have covered these topics.

Export data from SQL Server to Excel using stored procedures

  • There is a method in SQL Server called OPENROWSET method which is used to export data from SQL Server to Excel
  • OPENROWSET method has some requirements that need to be fulfilled before we can use this method
    • Administrator permissions to SQL Server Management Studio
    • enable “Show Advanced Options”
    • enable “Ad Hoc Distributed Queries”
  • Run SQL Server Management Studio as Administrator
  • Write the query following query to enable these options
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
GO
EXEC sp_configure 'Ad Hoc Distributed Queries',1;
RECONFIGURE;
GO
Export data from SQL Server to Excel
Configuring sp_configure
  • Give permissions to the Microsoft.ACE.OLEDB.12.0 driver by excecuting the following command
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
  • After successfully running the above commands, you have to create an Excel sheet with the same fields which are there in the database table
Export data from SQL Server 2019 to Excel
Field Names
  • Now you can write the query to export data from SQL Server to Excel
INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:UsersBladesDesktopexported_data.xls;','SELECT * FROM [Sheet1$]')
Select * from Employees;
  • Remember to set the Database path, Excel file name, Excel worksheet name and database name in the above query
  • You may encounter the following error while executing the query
  • This error states that the SQL Server is running on 64-bit architecture but Microsoft Access Database Engine only has 32-bit drivers installed

How to Export data from SQL Server to Excel

Version Error

This means you have to download the 64-bit Access Database Engine

You can download the 64-bit version of Access Database Engine from the specified link

Install Access Database Engine and this will install the 64-bit version of Microsoft.ACE.OLEDB.12.0 driver.

Now run the query again

INSERT INTO OPENROWSET('Microsoft.ACE.OLEDB.12.0','Excel 12.0;
Database=C:UsersBladesDesktopexported_data.xls;','SELECT * FROM [Sheet1$]')
Select * from Employees;
  • Now you can see, the query is run successfully
Export data from SQL Server 2019 to Excel using stored procedures
Success Message
  • You can open the Excel file and see if the data is exported
Export data from SQL Server to Excel using stored procedures
Exported Data
  • You can use this OPENROWSET method in your own stored procedure and export data from SQL Server to Excel.

You may like the following sql server articles:

  • SQL Server Substring Function
  • SQL Server Replace Function + Examples
  • SQL Server Convert String to Date

In this tutorial, we learned about the various methods of exporting the data from SQL Server to Excel. We solved some encountered errors also.

  • How to export data from SQL Server to Excel using Import and Export Wizard
  • How to export data from SQL Server to Excel automatically
  • How to export data from SQL Server to Excel using the query
  • How to import data from SQL Server into Excel using Data Connection Wizard
  • Export data from SQL Server to Excel using stored procedures

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

Понравилась статья? Поделить с друзьями:
  • Converter word en pdf gratuit en ligne
  • Convert sentence to word
  • Converter to word 2010
  • Converter qrp to excel
  • Convert scan pdf to excel