I need to upload multiple files (file1, file2, file3...) into tables (Table1, table2, table3...) in a sql server DB using OpenRowset function. All the files are kept in C:\download I use the following query which works fine.
INSERT INTO dbo.Table1
SELECT * from OpenRowset('MSDASQL','Driver={Microsoft Text Driver (*.txt;*.csv)};DefaultDir=C:\download;','select * from File1.csv' )
The question is how to pass the file name and table name as parameter.
Thanks Tony for your answer. I have put the sql in a stored procedure as follows.But it is much slower than the original hard coded file, and table names.Any suggestion to make it run faster.
ALTER proc [dbo].[ImportFiles]
@FilePath varchar(100) ,
@FileName varchar(100),
@TableName varchar(250)
AS
BEGIN
DECLARE @SqlStmt nvarchar(max)
DECLARE @ErrorCode int
SET @SqlStmt='Truncate table dbo.[' + @TableName +']'
EXEC(@SqlStmt);
-- i COULD PUT TRUNCATE statement in the sate statement as insert just before INSERT INTO.
set @SqlStmt=N'
INSERT INTO '+@TableName+N'
select *
from openrowset(''MSDASQL''
,''Driver={Microsoft Access Text Driver (*.txt, *.csv)};
DefaultDir='+@FilePath+N'''
,''select * from "'+@FileName+N'"'')'
EXEC(@SqlStmt);