To load data from an Excel (.xls or .xlsx) file into a Microsoft SQL Server (MSSQL) database, you can use SQL Server’s built-in functionality called “SQL Server Import and Export Wizard” or the “BULK INSERT” statement. I’ll walk you through both methods:
Method 1: SQL Server Import and Export Wizard:
- Open SQL Server Management Studio (SSMS) and connect to your MSSQL server.
- Right-click on the database where you want to import the data and select “Tasks” > “Import Data…”
- In the “Choose a Data Source” window, select “Microsoft Excel” as the data source and browse to the location of your Excel file.
- Follow the wizard’s instructions to select the Excel sheet and configure the settings for importing data, such as data type conversions and destination table.
- Once the import is configured, click “Next” and review the summary. Click “Finish” to start the import process.
Method 2: BULK INSERT SQL Statement:
If you prefer to use SQL code to load the data, you can use the “BULK INSERT” statement. However, similar to the previous method, you need to save the Excel data as a CSV file first.
- Save the Excel file as a CSV file. Make sure to use commas as the delimiter.
- Ensure that the SQL Server service account has access to read the CSV file.
- Use the following SQL code to load the CSV data into the MSSQL table:
BULK INSERT your_table_name FROM 'C:\Path\To\Your\CSV\File.csv' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n', FIRSTROW = 2 -- If the CSV file contains a header row, use FIRSTROW = 2 to skip it );
your_table_name with the name of the MSSQL table where you want to load the data. Ensure that the table structure matches the CSV data columns in the correct order.
FIELDTERMINATOR specifies the delimiter used in the CSV file. In this case, it’s a comma (
ROWTERMINATOR indicates the line termination character in the CSV file. The default value is ‘\n’, which is used for newline. If your CSV file has a different line termination character, update it accordingly.
FIRSTROW specifies the starting row for importing data. If your CSV file has a header row, use
FIRSTROW = 2 to skip it.
- Execute the SQL code to perform the bulk insert operation.
Both methods allow you to load data from Excel files into a MSSQL database efficiently. Choose the method that best suits your preference and requirements.