Microsoft sql server error 7301

I have been trying to configure a linked server to AD and have found plenty of write ups on how to do it, but have had zero luck with getting it to work.  I also read that the ability was removed after SQL 2008; is that correct?  I am running 2014 and am seeing the following error trying to expand the tree:
  • Remove From My Forums
  • Question

  • I have been trying to configure a linked server to AD and have found plenty of write ups on how to do it, but have had zero luck with getting it to work.  I also read that the ability was removed after SQL 2008; is that correct?  I am running 2014
    and am seeing the following error trying to expand the tree:

    TITLE: Microsoft SQL Server Management Studio
    ——————————

    Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)

    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&LinkId=20476

    ——————————
    ADDITIONAL INFORMATION:

    An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

    ——————————

    Cannot obtain the required interface («IID_IDBSchemaRowset») from OLE DB provider «ADSDSOObject» for linked server «ADSI». (Microsoft SQL Server, Error: 7301)

    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=12.00.4100&EvtSrc=MSSQLServer&EvtID=7301&LinkId=20476

    Then the following error when trying to query:

    SELECT * FROM OpenQuery(ADSI, ‘SELECT displayName FROM »LDAP://<DOMAIN>/DC=DOMAIN,DC=<DOMAIN>» WHERE objectCategory=»User» ‘)

    Msg 7321, Level 16, State 2, Line 1
    An error occurred while preparing the query «SELECT displayName FROM ‘LDAP://—-/DC=—-,DC=—-‘ WHERE objectCategory=’User’ » for execution against OLE DB provider «ADSDSOObject» for linked server «ADSI». 

    The linked server is set for ‘Be made by the login’s current security context’ and local to remote is configured SA to a domain account we use for lookups.  

    It does not seem to matter if I am logged in to the server with SQL or Windows credentials.  Thank you in advance for any guidance!


    -Drew

Answers

  • irst execute your query:

    EXEC sp_addlinkedserver ‘ADSI’, ‘Active
    Directory Service Interfaces’
    ,

    ‘ADSDSOObject’

    , ‘adsdatasource’

    GO

    Like daw21 explain before follow the detail steps:

    Second step go to the SqlServer management Studio and edit manually the Linkserver name ADSI:

    go to Server Objects/Linked Servers/  and right click on ADSI  select the option Properties and then go to Security.

    Select the option :         Be made using this security context:

    and there fill the user  and Password about the valid user with permission into Active Directory, not forget before the domainuser.


    Please click «Mark As Answer» if my post helped.

    • Marked as answer by

      Monday, August 24, 2015 5:57 PM

  • Additional Answer:

    AD remote account must be added to the SQL server and the ADSI linked server.  Only domain members required.  

    This really helped as I was able to step through the process to figure out the disconnect:

    http://www.databasejournal.com/features/mssql/article.php/3849891/Query-Active-Directory-Data-from-SQL-Server-using-T-SQL.htm


    -Drew

    • Marked as answer by
      dhcoop
      Monday, August 24, 2015 5:57 PM

1. С помощью процедуры sp_addlinkedserver создал связанный сервер(менял только первый параметр процедуры):

2. Так как у меня используется встроенная авторизация, то с помощью процедуры sp_addlinkedsrvlogin добавил логин для входа на связанный сервер(первый параметр это имя связанного сервера, назначенное в sp_addlinkedserver):

Если я правильно перевёл «BOL2000: OLE DB Provider for Microsoft Directory Services», то при использовании в MS SQL Server Windows-авторизации этот пункт не требуется.
3. Слегка допилил запрос из MSDN:

Проверенно на MSSQL2000(девелоперский) и SQL Server Express 2005(который с «продвинутыми фичами» ). Использовано BOL2000(описание процедур) и немного MSDN(Distributed Query)

По поводу работы примеров — в попадавшихся примерах к ошибкам приводило:
1. Неправильные кавычки(главный бич примеров в интернете, результат бездумного украшательства там где это недопустимо). А именно замена одинарных на двойные, использование двойных вместо одинарных внутри строки в OPENQUERY(в запросе выше все символы кавычек одинарные).
2. Схема может отличаться, тогда выбираемые колонки или условия будут не верны. Однако QA сообщит лишь о том что «что-то не срослось» при работе с «ADSDSOObject» . В этом случае стоит попробовать убрать явно задаваемые имена колонок. Например так:

Получим полный набор данных, анализируем что мы имеем в реальности и затачиваем запрос под нашу схему.
3. Строка авторизации. В примерах пользователь для входа на сервер для п.2 указывался в стиле AD, в результате чего QA ругался что отсутствуют права доступа к данным.

  • Рейтинг : [ 41 | 0 ]

    Re: SQL: Получить список компьютеров домена

    2 Bes Yara: Очень благодарен Вам за ответ !. Т.к тема по прежнему актуальна для меня. Но к сожалению я до сих пор бьюсь всё об тот же косяк. При выполнении любого запроса получаю:

    An error occurred while preparing the query »
    SELECT name
    FROM ‘LDAP://DC=BANK,DC=local’
    WHERE objectCategory=’computer’
    » for execution against OLE DB provider «ADSDSOObject» for linked server «BANK».

    Домен у нас BANK.

    Выполнял всё вот так

    DomainAdminPassword — указывал пароль доменного Администратора.

    Линковка, как и раньше прошла успешно. Ранее коннектил AD под именем ADSI.

    Решил просто через интерфейс студии пощупать BANK в списке прилинкованных серверов. Дойдя до defaulttables получаю сообщение:

    Failed to retrieve data for this request. (Microsoft.SqlServer.SmoEnum)

    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&LinkId=20476

    An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

    Cannot obtain the required interface («IID_IDBSchemaRowset») from OLE DB provider «ADSDSOObject» for linked server «BANK». (Microsoft SQL Server, Error: 7301)

    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&ProdVer=09.00.5000&EvtSrc=MSSQLServer&EvtID=7301&LinkId=20476

    Есть у меня подозрения, что либо какие то службы на доменконтроллере остановлены, либо порты какие то закрыты, либо и правда какой то Shem-ы нету для формирования данных в нормальном виде. В общем — хрень полная. )

    Источник

    Microsoft sql server error 7301

    This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

    Answered by:

    Question

    I have been trying to configure a linked server to AD and have found plenty of write ups on how to do it, but have had zero luck with getting it to work. I also read that the ability was removed after SQL 2008; is that correct? I am running 2014 and am seeing the following error trying to expand the tree:

    TITLE: Microsoft SQL Server Management Studio
    ——————————

    Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)

    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&LinkId=20476

    An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

    Cannot obtain the required interface («IID_IDBSchemaRowset») from OLE DB provider «ADSDSOObject» for linked server «ADSI». (Microsoft SQL Server, Error: 7301)

    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=12.00.4100&EvtSrc=MSSQLServer&EvtID=7301&LinkId=20476

    Then the following error when trying to query:

    SELECT * FROM OpenQuery(ADSI, ‘SELECT displayName FROM »LDAP:// /DC=DOMAIN,DC= » WHERE objectCategory=»User» ‘)

    Msg 7321, Level 16, State 2, Line 1
    An error occurred while preparing the query «SELECT displayName FROM ‘LDAP://—-/DC=—-,DC=—-‘ WHERE objectCategory=’User’ » for execution against OLE DB provider «ADSDSOObject» for linked server «ADSI».

    The linked server is set for ‘Be made by the login’s current security context’ and local to remote is configured SA to a domain account we use for lookups.

    It does not seem to matter if I am logged in to the server with SQL or Windows credentials. Thank you in advance for any guidance!

    Источник

    Microsoft sql server error 7301

    This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

    Answered by:

    Question

    I have been trying to configure a linked server to AD and have found plenty of write ups on how to do it, but have had zero luck with getting it to work. I also read that the ability was removed after SQL 2008; is that correct? I am running 2014 and am seeing the following error trying to expand the tree:

    TITLE: Microsoft SQL Server Management Studio
    ——————————

    Failed to retrieve data for this request. (Microsoft.SqlServer.Management.Sdk.Sfc)

    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&LinkId=20476

    An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)

    Cannot obtain the required interface («IID_IDBSchemaRowset») from OLE DB provider «ADSDSOObject» for linked server «ADSI». (Microsoft SQL Server, Error: 7301)

    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft%20SQL%20Server&ProdVer=12.00.4100&EvtSrc=MSSQLServer&EvtID=7301&LinkId=20476

    Then the following error when trying to query:

    SELECT * FROM OpenQuery(ADSI, ‘SELECT displayName FROM »LDAP:// /DC=DOMAIN,DC= » WHERE objectCategory=»User» ‘)

    Msg 7321, Level 16, State 2, Line 1
    An error occurred while preparing the query «SELECT displayName FROM ‘LDAP://—-/DC=—-,DC=—-‘ WHERE objectCategory=’User’ » for execution against OLE DB provider «ADSDSOObject» for linked server «ADSI».

    The linked server is set for ‘Be made by the login’s current security context’ and local to remote is configured SA to a domain account we use for lookups.

    It does not seem to matter if I am logged in to the server with SQL or Windows credentials. Thank you in advance for any guidance!

    Источник

    Microsoft sql server error 7301

    This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

    Answered by:

    Question

    Answers

    For Microsoft.ACE.OLEDB.12.0 I managed to solve the problem by checking:

    — Nested queries
    — Allow inprocess

    in Microsoft.ACE.OLEDB.12.0 -> Properties.

    • Marked as answer by Kalman Toth Editor Tuesday, November 30, 2010 4:37 PM

    Please see the following link:

    Hope this helps.

    Regards,

    Thank you for your suggestion. Unfortunately, unchecking the «Allow InProcess» property on the Jet provider DID NOT solve my problem. I merely exchanged the 7303 error for a 7399 error indicating «Access denied». The current MDB file I am trying to connect to is NOT secured and DOES NOT require a password.

    Is There something else I am missing?

    Please provide user ADMIN with no password.

    Hope this helps.

    Regards,

    Well I got passed the initial 7303 and 7399 errors by unchecking the «Allow InProcess» property and setting the login as «Admin» with no password, but I have a new error. I can successfully test the connection, but when I run a query against it I get the following messages:

    Msg 7399, Level 16, State 1, Line 1
    The OLE DB provider «Microsoft.Jet.OLEDB.4.0» for linked server «LinkedMDB» reported an error. Access denied.
    Msg 7301, Level 16, State 2, Line 1
    Cannot obtain the required interface («IID_IDBCreateCommand») from OLE DB provider «Microsoft.Jet.OLEDB.4.0» for linked server «LinkedMDB».

    What is really odd is that, although the first message indicates «Access denied», the query results contain the proper column headings for the table I am querying without returning any data. The database is not secured, so I don’t understand why I can see the column headings but not the data. I also noticed that there is a new «ldb» file in the same directory as the database, so it doesn’t appear to be a permission issue with the database location.

    I am happy we are facing different error.

    Are you authenticated on SQL server using a SQL login? That may explain error 7399, because that SQL login does not have permissions to access the Microsoft Access database on the folder where it is located. Create the linked server using windows authentication login that has proper permissions and verify SQL Server service account has proper permissions to the folder where the Access database is located.

    Use the following guide to create the linked server:

    Hope this helps.

    Regards,

    Actually, I created the linked server from within the SQL Enterprise Manager while logged on using a domain account. The account used to create the linked server has administrative permissions on both the SQL environment AND the server itself. I understand that when the linked server operates it uses the service account. I am using a domain account for the SQL service account and I verified that this account has full permissions on the directory where the MDB file resides AND any of the “temp” directories that SQL may use on the server. Since this appears to be a permissions issue, I decided to logon to the SQL server as the service account, open the Enterprise Manager and perform my query against the linked server. THAT WORKED! I don’t understand why the other “administrative” account cannot perform the query when the service account can. I really don’t want to use the SQL service account whenever I need to query data from this source. What do I need to do to enable other domain accounts to perform queries against this linked server?

    Thanks again for all the help!

    Please go to the Properties of the linked server, click on the Security page, and use the option “Be made using this security context”, or one of the other options.

    Hope this helps.

    Regards,

    • Edited by Kalman Toth Editor Wednesday, September 26, 2012 10:03 PM

    I got a similar problem with linked servers in SQL Server 2005

    Im trying to make a query to a Access 2000 Database using a OLE DB Provider for Jet (Linked Database) and SQL Authentication. The datasource is a .mdb file available in a shared directory in another Windows Server.

    I have no problems with the linked server while using Windows Authentication with the proper permisions in the shared directory. But when i try with SQLAuthentication i got the following error:

    OLE DB provider «Microsoft.Jet.OLEDB.4.0» for linked server «TMCAccess2» returned message «The Microsoft Jet database engine cannot open the file ‘\wintermute_13mediamdbacd4.mdb’. It is already opened exclusively by another user, or you need permission to view its data.».
    Msg 7303, Level 16, State 1, Line 1
    Cannot initialize the data source object of OLE DB provider «Microsoft.Jet.OLEDB.4.0» for linked server «TMCAccess2».

    Testing with multiple configurations for the security results in diferent errors like this one:

    OLE DB provider «Microsoft.Jet.OLEDB.4.0» for linked server «TMCAccess2» returned message «Cannot start your application. The workgroup information file is missing or opened exclusively by another user.».
    Msg 7399, Level 16, State 1, Line 1
    The OLE DB provider «Microsoft.Jet.OLEDB.4.0» for linked server «TMCAccess2» reported an error. Authentication failed.
    Msg 7303, Level 16, State 1, Line 1
    Cannot initialize the data source object of OLE DB provider «Microsoft.Jet.OLEDB.4.0» for linked server «TMCAccess2».

    Any advice or work around for this situation? Is posible to use linked servers in a shared directory while using SQL Authentication?

    Источник

  • Good Morning,

    I am looking for some assistance.

    I have created a linked server as follows: EXEC sp_addlinkedserver ‘ADSI’,

    ‘Active Directory Services 2.5’, ‘ADsDSOObject’, ‘adsdatasource’

    I now go to EM and open the linked server, ADSI properties.  I have no local

    logins defined, I click the «Be made without using a security context».  I

    then try to click on tables.  I have also tried to use a security context.

    I get the following error: error 7301: Could not obtain a required interface

    from OLE DB provider ‘ADsDSOObject’

    Properties

    General Tab:

    Linked Server: ADSI

    Provider Name: ADsDSOObject

    Datasource: adsdatasource

    Provider String:

    Location:

    Catalog:

    On the server options tab, I have Data Access checked off.

    Sql Server Version: 7.0 Server O/S: NT SP 4

    Exchange Ver. 5.5 Server O/S: NT

    Can you please help? Any information may be useful.

    Thx,

    Jeff

    March 14, 2005 at 8:00 am

    This was removed by the editor as SPAM

    Huang John

    Valued Member

    Points: 52

    Hi Jeff

    I am new to using linked server to access AD. However after some poking around and Googling, I was able to do so.

    Here is what I have working for me:

    EXEC sp_addlinkedserver ‘ADSI’, ‘Active Directory Services 2.5’, ‘ADSDSOObject’, ‘adsdatasource’ —I am not sure if it’s case sensitive or not, I have seen some discussion on this issue. You can copy & paste to try it.

    EXEC sp_addlinkedsrvlogin ‘ADSI’, ‘false’, ‘sa’, ‘YourDomainAnyDomainAccount’, ‘AccountPassword’ —it seems any domain account would work, I think default AD is open for query.

    —I use the following OpenQuery to get users’ info in a particular OU.

    SELECT TOP 100 PERCENT * FROM OpenQuery(ADSI,

    ‘SELECT telephoneNumber, givenName, sn, mail, title, department, physicalDeliveryOfficeName, sAMAccountName, displayName

    FROM »LDAP://DCServerName.YourDomainName/OU_To_Be_Searched» where objectClass = »User» AND objectCategory= »person» AND sAMAccountName=»*»’)

    ORDER BY displayName

    I am currently having problem using OLE DB via linked server to Exchange 2003. If you know or have been successfully appcomplished this, please let me know.

    Hopefully this can help you as well.

    John

    Используя SQL Server 2016, я работаю над унаследованной системой, которая требует, чтобы ее ночной импорт выполнялся с помощью массовой вставки. Я знаю, что SSIS — лучший вариант, но мне недоступен.

    Я загружаю файл с локального компьютера с помощью следующей команды:

    BULK INSERT DataImports.staging_Companies
    FROM 'D:xxxxxcompanies_20180802093057.txt'
    WITH (BATCHSIZE = 1000
    ,     DATAFILETYPE = 'char'
    ,     FIRSTROW = 2
    ,     FIELDTERMINATOR = '   ' -- Tab Character here
    ,     ROWTERMINATOR = 'n'
    ,     ERRORFILE = 'D:xxxxxcompany_errors.txt');
    

    Файл формата не используется, и из-за нашей динамической обработки мы не сможем его использовать. При загрузке файла я получаю сообщение об ошибке:

    Msg 7301, Level 16, State 2, Line 4
    Cannot obtain the required interface («IID_IColumnsInfo») from OLE DB provider «BULK» for linked server «(null)».

    По общему мнению, существует проблема с ограничителями строк / строк. Здесь дело обстоит не так. Проблема, похоже, связана с размером файла или количеством строк. Импорт работает нормально до 2482 строк, но падает до 2483. Перемещая строки, я исключил ошибку в самих данных.

    При превышении размера файла / количества строк команда вообще не запускается. Я добавил триггер в целевую таблицу и размер пакета и вижу результаты для меньшего размера и совсем не вижу результатов для большего размера.

    Исходя из этого, мне интересно, есть ли что-то, что вызывает прерывание при чтении файла и обрезает его на полпути через строку? Я использовал и поддерживал эту систему какое-то время и видел, как раньше обрабатывались гораздо большие файлы с точки зрения как строк, так и размера данных.

    Обновлять:

    Только что перенесли этот файл на свой локальный компьютер и выполнили импорт в моей тестовой базе данных (SQL2017). Массовая вставка прошла нормально, без ошибок. Моя локальная версия 14.0.1000.169, клиент-сервер 13.0.1601.5.

    Также протестирован на другом сервере 2016 года (13.0.4474.0), и все прошло нормально. Есть ли что-нибудь в настройке сервера, что может вызвать эту проблему? Или даже что-то из основной файловой системы? Хватаюсь за соломинку.

    Любые идеи с благодарностью получены.

    Я пытаюсь вставить через файл CSV, который, кстати, будет выполняться каждый день через процедуру, но выдает ту же ошибку.

    Msg 7301, уровень 16, состояние 2, строка 16
    Невозможно получить требуемый интерфейс («IID_IColumnsInfo») от поставщика OLE DB «BULK» для связанного сервера «(null)».

    В таблице, которую я пытаюсь импортировать, я поместил все поля как nvarchar и все они должны содержать не менее 500 символов, потому что я думал, что это проблема.

    Этот CSV-файл я экспортирую через PowerShell следующим образом:

    Export-Csv -Path $DirPath -Delimiter ';' -NoTypeInformation -Encoding UTF8
    

    В файле 40 столбцов и 685 строк, я уже пытался сохранить файл CSV с разделителем ‘,’ и ‘;’ разделитель, но оба имеют одну и ту же ошибку.

    Я попытался выполнить массовую вставку несколькими способами, как показано ниже, но безуспешно.

    BULK INSERT DEV_DS_SANTOGRAU..GB_TBIMP_FOTOS_CSV
    FROM 'C:UsersuserbiDesktopProjetos-Santo-GrauProjeto1-RelatoriodeEstoqueTBIMP_FOTOS_CSV.csv'
    WITH (FORMAT = 'CSV', 
          --MAXERRORS = 0,
          --CODEPAGE = '65001',
          CODEPAGE = 'ACP',
          --FIELDQUOTE = '"', 
          FIELDTERMINATOR ='";"', 
          --ROWTERMINATOR ='"n"',
          ROWTERMINATOR = 'rn',
          --ROWTERMINATOR = "0x0a"
          FIRSTROW = 2,
          ERRORFILE = 'C:UsersuserbiDesktopProjetos-Santo-GrauProjeto1-RelatoriodeEstoqueTBIMP_FOTOS_CSV_ERROS.csv');
    

    После того, как он экспортировал файл CSV и TXT с ошибками, используя приведенный выше код, данные были такими (но не в исходном файле):

    enter image description here

    Что я должен делать?

    Мне бы этого не хотелось, но если бы можно было игнорировать эти записи, но вставка завершилась, было бы меньше хуже.

    Информация:

    • SQL Server 2019 (v15.0.18330.0)
    • Объекты управления SQL Server (SMO) v16.100.37971.0
    • Microsoft SQL Server Management Studio версии 18.5

    1 ответ

    Лучший ответ

    Обычно проще BULK INSERT данных с помощью файла форматирования. Используйте служебную программу bcp.exe для создания файла форматирования с помощью следующей команды:

    bcp.exe DEV_DS_SANTOGRAU..GB_TBIMP_FOTOS_CSV format nul -c -t; -f C:TempTBIMP_FOTOS_CSV.fmt -S(local) -T
    

    Куда:

    • DEV_DS_SANTOGRAU..GB_TBIMP_FOTOS_CSV — это таблица Database.Schema.Table, с которой мы взаимодействуем.
    • format определяет режим создания файла формата.
    • nul указывает файл данных ввода / вывода, что в данном случае означает «не записывать никаких данных».
    • -c определяет символьный режим в отличие от собственного (двоичного) режима.
    • -t; указывает на использование ; в качестве символа разделителя полей.
    • -f C:TempTBIMP_FOTOS_CSV.fmt указывает путь для записи файла формата относительно вашего локального компьютера.
    • -S(local) — это SQL-сервер, к которому нужно подключиться, в моем случае — (local).
    • -T означает надежную аутентификацию (аутентификация Windows), используйте вместо этого -uUsername и -pPassword, если у вас есть аутентификация входа SQL.

    Это создает файл формата примерно следующего вида (у вас будет больше и разных столбцов):

    14.0
    2
    1       SQLCHAR             0       510     ";"      1     Filename                 SQL_Latin1_General_Pref_CP1_CI_AS
    2       SQLCHAR             0       510     "rn"   2     Resolution               SQL_Latin1_General_Pref_CP1_CI_AS
    

    Теперь в SSMS вы должны иметь возможность запустить что-то вроде следующего, чтобы импортировать файл данных (при необходимости скорректируйте пути к файлам относительно вашего SQL Server):

    BULK INSERT DEV_DS_SANTOGRAU..GB_TBIMP_FOTOS_CSV
    FROM 'C:TempTBIMP_FOTOS_CSV.csv'
    WITH (
        CODEPAGE = '65001',
        DATAFILETYPE = 'char',
        FORMAT = 'CSV', 
        FORMATFILE = 'C:TempTBIMP_FOTOS_CSV.fmt'
    );
    

    — редактировать —

    О SQL Server и поддержке международных символов .

    У SQL Server и UTF-8 была немного неоднородная история, только частичная поддержка в SQL Server 2016 и поддержка только кодовых страниц UTF-8 в SQL Server 2019. Импорт и экспорт файлов с международными символами по-прежнему лучше всего обрабатывать с помощью UTF -16 закодированных файлов. Изменения в рабочем процессе заключаются в следующем …

    В PowerShell используйте кодировку Unicode вместо UTF8:

    Export-Csv -Path $DirPath -Delimiter ';' -NoTypeInformation -Encoding Unicode
    

    При создании файла формата BCP используйте переключатель -w (для widechar) вместо -c (для char):

    bcp.exe DEV_DS_SANTOGRAU..GB_TBIMP_FOTOS_CSV format nul -w -t; -f C:TempTBIMP_FOTOS_CSV-widechar.fmt -S(local) -T
    

    Это приводит к тому, что столбцы SQLCHAR записываются как SQLNCHAR, иначе. поддержка национального характера:

    14.0
    2
    1       SQLNCHAR            0       510     ";"        1     Filename                 SQL_Latin1_General_Pref_CP1_CI_AS
    2       SQLNCHAR            0       510     "rn"   2     Resolution               SQL_Latin1_General_Pref_CP1_CI_AS
    

    При использовании BULK INSERT укажите DATAFILETYPE = 'widechar' вместо DATAFILETYPE = 'char' и укажите кодовую страницу, например:

    BULK INSERT GB_TBIMP_FOTOS_CSV
    FROM 'C:TempTBIMP_FOTOS_CSV.csv'
    WITH (
        DATAFILETYPE = 'widechar',
        FORMATFILE = 'C:TempTBIMP_FOTOS_CSV-widechar.fmt'
    );
    


    2

    AlwaysLearning
    12 Июн 2020 в 00:58

    Понравилась статья? Поделить с друзьями:
  • Microsoft sql server error 262 как исправить
  • Microsoft office word сбой активации продукта как исправить
  • Microsoft office cannot open this file because some parts are missing or invalid как исправить
  • Microsoft office 2016 сбой активации продукта как исправить
  • Microsoft office 2013 сбой активации продукта как исправить