TSQL BULK INSERT,带有来自.txt文件的自动递增密钥

时间:2017-04-21 19:45:46

标签: sql-server tsql

error im getting

这是要插入已经创建的表中:

 CREATE TABLE SERIES(

SERIES_NAME VARCHAR(225) NOT NULL UNIQUE, --MADE VARCHAR(225) & UNIQUE FOR FK REFERENCE
ONGOING_SERIES BIT, --BOOL FOR T/F IF SERIES IS COMPLETED OR NOT
RUN_START DATE, 
RUN_END DATE,
MAIN_CHARACTER VARCHAR(20),
PUBLISHER VARCHAR(12),
S_ID INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
CONSTRAINT chk_DATES CHECK (RUN_START < RUN_END)
)       

,文本文件组织为:

  

GREEN LANTERN,0,2005-07-01,2011-09-01,HAL JORDAN,DC

     

SPIDERMAN,0,2005-07-01,2011-09-01,PETER PARKER,MARVEL

我已经尝试在.txt文件中的每一行末尾添加逗号 我也尝试过添加,&#39; &#39;到每行的末尾。 有什么建议吗?

2 个答案:

答案 0 :(得分:0)

从BULK INSERT中删除KEEPIDENTIY,因为它指定您要使用源文本文件中的值作为IDENTITY。

如果仍然失败,请尝试在排除IDENTITY字段的表格上添加一个VIEW,然后插入其中,例如:

CREATE VIEW SeriesBulkInsertTarget 
AS
    SELECT Series_Name,
        Ongoing_Series,
        Run_Start,
        Run_End,
        Main_Character,
        Publisher
    FROM SERIES

答案 1 :(得分:0)

实际上,KEEPIDENTITY可防止发生大量插入物。但是,删除语句无法解决问题。

SELECT * , CAST(RIGHT(FileNo, 3) AS NUMERIC) AS IntFileNo
FROM dbo.ExportLcs AS A
OUTER APPLY (
    SELECT SUM(ReceivedTTUsd) AS TtTotal
        , SUM(ReceivedPDCUsd) AS PdcTotal
        , SUM(CASE WHEN ReceivedPDCUsd > 0 THEN 1 ELSE 0 END) AS PdcCashCount
        , SUM(CASE WHEN ReceivedPDCUsd > 0 THEN ConvertRate ELSE 0 END) AS PdcRateTotal
        , SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END) AS PdcTotalUsd
        , COUNT(ExportLcId) AS TotalPaymentCount
    FROM dbo.ExportPayments AS G
    WHERE A.ExportLcId = G.ExportLcId
    HAVING (SUM(ReceivedPDCUsd) + SUM(CASE WHEN ConvertRate > 0 THEN CEILING(ReceivedPDCUsd / ConvertRate) ELSE 0 END)) > 0
) AS G;

批量插入期望更新所有列。解决此问题的另一种方法是为文本文件添加格式文件,请参阅MS Docs - Use a Format File to Bulk Import Data

您可以使用以下命令为文本文件创建格式文件。

Msg 4864, Level 16, State 1, Line 13
Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 7 (S_ID).

删除最后一行,更新列数,并将最后一个逗号替换为行终止符。结果如下所示。

bcp yourdatabase.dbo.series format nul -c -f D:\test.fmt -t, -T