将数据从文本文件导入到sql表中

时间:2014-10-31 11:48:47

标签: mysql sql sql-server sql-server-2008 sqlite

我在文本文件(field1,field2,fiel3,field4),(field1,field2,fiel3,field4)中有数据,... 我想在sql server表中导入它.. plz help

(699,429,1,'2000-11-30 04:34:16'),(699,2170,2,'2000-11-30 04:07:23'),(699,2171,2,'2000-11-30 04:21:44'),(699,919,4,'2001-04-05 03:21:50'),(699,3160,5,'2000-11-30 04:16:29'),(699,1250,3,'2001-04-05 03:18:20')

2 个答案:

答案 0 :(得分:0)

请尝试以下方法:

BULK INSERT DBNAME.dbo.TABLENAME FROM  FULLPATH  WITH (KEEPIDENTITY,  FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' )

请记得填写数据库名称,表名和FullPath。

希望这有帮助。

答案 1 :(得分:0)

从文本文件中读取数据并首先将其放入SQL Server。然后尝试使用t-sql中可用的所有功能来操纵它。

我会做类似......

查询

DECLARE @FileTable TABLE (FileData NVARCHAR(MAX))

INSERT INTO @FileTable
SELECT BulkColumn 
FROM OPENROWSET(BULK N'C:\Path_to_Text_File\Test_Text_FIle.txt', SINGLE_CLOB) AS Contents

;WITH CTE AS(
 SELECT REPLACE(
         REPLACE(
           REPLACE(
              REPLACE(FileData, '),(', '|')
               , '(', '') 
             , ')', '')
            , '''', '')   AS TextData
              FROM @FileTable
 ),Column_Split AS
 (
 SELECT CONVERT(XML,'<Columns><Column>'  
   + REPLACE(val,',', '</Column><Column>') + '</Column></Columns>') [Columns]
 FROM CTE C CROSS APPLY dbo.split(c.TextData, '|')
)
SELECT      
   [Columns].value('/Columns[1]/Column[1]','varchar(100)') AS Column1,    
   [Columns].value('/Columns[1]/Column[2]','varchar(100)') AS Column2,
   [Columns].value('/Columns[1]/Column[3]','varchar(100)') AS Column3,
   [Columns].value('/Columns[1]/Column[4]','varchar(100)') AS Column4
 FROM Column_Split

结果

╔═════════╦═════════╦═════════╦═════════════════════╗
║ Column1 ║ Column2 ║ Column3 ║       Column4       ║
╠═════════╬═════════╬═════════╬═════════════════════╣
║     699 ║     429 ║       1 ║ 2000-11-30 04:34:16 ║
║     699 ║    2170 ║       2 ║ 2000-11-30 04:07:23 ║
║     699 ║    2171 ║       2 ║ 2000-11-30 04:21:44 ║
║     699 ║     919 ║       4 ║ 2001-04-05 03:21:50 ║
║     699 ║    3160 ║       5 ║ 2000-11-30 04:16:29 ║
║     699 ║    1250 ║       3 ║ 2001-04-05 03:18:20 ║
╚═════════╩═════════╩═════════╩═════════════════════╝

分割功能定义

CREATE FUNCTION [dbo].[split](  
  @delimited NVARCHAR(MAX),  
  @delimiter NVARCHAR(100)  
) RETURNS @t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))  
AS  
BEGIN  
  DECLARE @xml XML  
  SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'  

  INSERT INTO @t(val)  
  SELECT  r.value('.','varchar(MAX)') as item  
  FROM  @xml.nodes('/t') as records(r)  
  RETURN  
END