BCP转换说明的无效字符

时间:2019-04-29 08:26:05

标签: sql-server bcp sqlbulkcopy sql-server-2017

我正在尝试将包含这些内容的CSV导入我的SQL Server数据库。

数据:

static class Win32Console
{
    public static Stream GetConsoleStreamWithImmediateInput()
    {
        var handle = GetStdHandle(STD_INPUT_HANDLE);

        if (handle.IsInvalid) throw new Win32Exception();

        try
        {
            if (!GetConsoleMode(handle, out var mode)) throw new Win32Exception();

            mode &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);

            if (!SetConsoleMode(handle, mode)) throw new Win32Exception();
        }
        catch
        {
            handle.Close();
            throw;
        }

        return new FileStream(handle, FileAccess.Read);
    }

    const int STD_INPUT_HANDLE = -10;

    const int ENABLE_LINE_INPUT = 0x0002;
    const int ENABLE_ECHO_INPUT = 0x0004;

    [DllImport("Kernel32.dll", SetLastError = true)]
    static extern SafeFileHandle GetStdHandle(int nStdHandle);

    [DllImport("Kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetConsoleMode(SafeFileHandle hConsoleHandle, out int mode);

    [DllImport("Kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetConsoleMode(SafeFileHandle hConsoleHandle, int mode);
}

格式文件:

tranche_d_age
<18
18_24
25_34
35_44
45_60
>60

在数据库中,我创建了一个具有以下规范的表:

14.0
1
1       SQLCHAR             0       0      "\n"   2     tranche_d_age_id                                      French_CI_AS

这是我发出的bcp命令:

DROP TABLE IF EXISTS [dbo].[ref_tranches_age]

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ref_tranches_age](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [tranche_d_age_id] [varchar](max) NULL
)
GO

响应:

bcp [xxx].dbo.tranches_age in 'ref_tranches_age.csv' -U 'xxx' -P 'xxx' -S 'xxx' -f bcp_ref_tranches_age.fmt

在我看来,响应包含csv文件中7行的7条错误消息。 (我可能是错的)

我发现这2个线程说我的源文件中不应有空格,也不应插入标识列中。除非我错了,否则我不会这么做。

1 个答案:

答案 0 :(得分:1)

在创建文件ref_tranches_age.csv时,它可能包含lineterminator ='\ r \ n'作为行分隔符,文件bcp_ref_tranches_age.fmt指定了lineterminator ='\ n'。因此,您有两个选择,第一个是在创建csv文件时,指定lineterminator ='\ n'和voila,或者在bcp_ref_tranches_age.fmt文件中添加lineterminator ='\ r \ n',如下所示:

bcp [xxx] .dbo.tranches_age in 'ref_tranches_age.csv' -U 'xxx' -P 'xxx' -S 'xxx' -f bcp_ref_tranches_age.fmt -r "\ r \ n"

.fmt文件将如下所示:

14.0 
1 
1 
SQLCHAR     0   0   "\r\n"  2   tranche_d_age_id French_CI_AS
相关问题