I want to import data from my Excel sheet into my SQL Server 2008 database.
I have an Excel sheet that contains different columns :
Service tag | marque | Type | Serial
FGT3456 | DELL | UC | Optiplex 760
and my table has the same structure, but instead of varchar
values, I have foreign keys (the IDs)
Example (table material)
Service tag | marque| Type | Serial
FGT3456 | 1 | 18 | 27
What I want to do is to fetch into the column marque
in the Excel sheet, get all the marque values, compare the values to those in my table, get all them IDs and in the end insert the Ids into my table material.
I tried this code but it's showing an error
Incorrect syntax near the keyword 'SELECT'.
Incorrect syntax near ')'.
Invalid object name 'SQL'.
This is my code
ALTER PROCEDURE [dbo].[spx_Import]
@SheetName varchar(20),
@FilePath varchar(100),
@HDR varchar(3),
@TableName varchar(50)
AS
BEGIN
DECLARE @SQL nvarchar(1000)
DECLARE @SQL1 nvarchar(1000)
DECLARE @SQL2 nvarchar(1000)
SET @SQL = 'SELECT idMarque FROM MarqueMateriel WHERE marque = SELECT (marque) FROM OPENDATASOURCE'
SET @SQL1 = 'INSERT INTO Material (Service tag) SELECT (service tag) FROM OPENDATASOURCE'
SET @SQL2 = 'INSERT INTO Material (MARQUE) SELECT * FROM '+@SQL''
SET @SQL = @SQL + '(''Microsoft.ACE.OLEDB.12.0'',''Data Source='
SET @SQL = @SQL + @FilePath + ';Extended Properties=''''Excel 12.0;HDR='
SET @SQL = @SQL + @HDR + ''''''')...['
SET @SQL = @SQL + @SheetName + ']'
SET @SQL1 = @SQL1 + '(''Microsoft.ACE.OLEDB.12.0'',''Data Source='
SET @SQL1 = @SQL1 + @FilePath + ';Extended Properties=''''Excel 12.0;HDR='
SET @SQL1 = @SQL1 + @HDR + ''''''')...['
SET @SQL1 = @SQL1 + @SheetName + ']'
SET @SQL1 = @SQL2 + '(''Microsoft.ACE.OLEDB.12.0'',''Data Source='
SET @SQL1 = @SQL2 + @FilePath + ';Extended Properties=''''Excel 12.0;HDR='
SET @SQL1 = @SQL2 + @HDR + ''''''')...['
SET @SQL1 = @SQL2 + @SheetName + ']'
EXEC sp_executesql @SQL
EXEC sp_executesql @SQL1
EXEC sp_executesql @SQL2
END
In the first query @SQL
, I retrieve all IDs from the table Material where the name(marque) equals to those in the Excel sheet.
In the 2nd query, @SQL1
, I insert the serviceTag
values from the Excel sheet into the table
In the last one @SQL2
, I insert into the table material the IDs retrieved from the first query
Is my logic correct ?? Is this how I should proceed ?? Please I need help !!