Upload csv Files Using SQL Server OpenRowSet Function

百般思念 提交于 2020-01-13 06:48:37

问题


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);

回答1:


You will have to build your query using dynamic SQL to pass a parameter in to the OPENROWSET function. The code to build the dynamic SQL can then be placed in a stored procedure to make it easier to call.

The code to create the SQL dynamically would be something like:

DECLARE @tableName varchar(10);
DECLARE @importFile varchar(10);
SET @tableName = 'Table1'
SET @importQuery= 'File1.csv';
EXEC( 'INSERT INTO ' + @tableName + 'SELECT * from OpenRowset(''MSDASQL'',''Driver={Microsoft Text Driver (*.txt;*.csv)};DefaultDir=C:\download;'',''SELECT * FROM ' + @importFile + ''' )'

NOTE: You'll have to check the quotes are correct, I don't have access to SQL server at the moment to check the syntax.



来源:https://stackoverflow.com/questions/7319895/upload-csv-files-using-sql-server-openrowset-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!