通过存储过程将数据从Excel导入SQL Server

时间:2011-04-21 13:22:08

标签: sql vb.net stored-procedures import

我在网上找到了一些关于如何通过vb将excel导入sql的例子。但我可以通过存储过程来完成吗?

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

所以,我可以通过:

('Microsoft.Jet.OLEDB.4.0', 
        'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
        'SELECT * FROM [SheetName$]')

作为SQL Server SP的参数?或者我怎么能保护自己免受sql注射和其他攻击?

2 个答案:

答案 0 :(得分:0)

您可以设置SSIS包并将其从Excel传输到SQL Server(或平面文件等)

答案 1 :(得分:0)

DECLARE @bcpCommand varchar(2000), @dt varchar(15), @fn varchar(20), @fn1 varchar(30), @ty char(4) = '.csv', @path varchar(15) = 'C:\sive\'

SELECT @dt = convert(varchar,getdate(),112)

SELECT @fn = 'TblEnquiry_bcp'

SELECT @fn1 = @fn+'_'+@dt+@ty

SELECT @bcpCommand = 'ren '+ @path+@fn + @ty +' ' + @path + @fn1

SELECT @bcpCommand = 'ren '+ @path+@fn + @ty +' ' + @fn1

EXEC xp_cmdshell @bcpCommand

select @bcpCommand = 'bcp "SELECT hc.RegNo VehicleNo, convert(date,hv.DisplayDateTime,112) RunningDate,

       COUNT(1) AS NoofCountPlayed, hv.BoardTransID BoardTransId

       FROM Advertisementlog hv  WITH (NOLOCK)

       INNER JOIN VehiclesM hc WITH (NOLOCK) ON hv.BoardTransID=hc.RTONo

       WHERE convert(varchar(30),displaydatetime,112)>=convert(date,DATEADD(month, DATEDIFF(month, 0, getdate()), 0),112)

       AND convert(varchar(30),displaydatetime,112) <= convert(date,getdate(),112)

       AND hc.RTONo IS NOT NULL AND hc.RTONo <>''

       GROUP BY hc.RegNo, convert(date,hv.DisplayDateTime,112), hv.BoardTransID" queryout C:\Sive\TblEnquiry_bcp.csv -t, -c -T -SHABXC3NKSD -d WeddingVowsUAT'



EXEC xp_cmdshell @bcpCommand

select @bcpCommand = 'copy /b c:\sive\TblEnquiry_Header.csv+c:\sive\tblenquiry_bcp.csv c:\sive\test_bcp.csv'

EXEC xp_cmdshell @bcpCommand