Ole db core services где находится

от admin

How to get a list of installed OLE DB providers?

Microsoft Excel allows import of data from «Other Sources». One of the options is to use an OLE DB provider.

How to get a list of available OLE DB providers?

8 Answers 8

If you have powershell available, just paste this into a powershell command prompt:

I am answering my own question because this was harder to find that I expected. Google-fu could only answer part of my question; I needed to synthesize information from various blog entries and official documentation.

Below is VBScript you can copy/paste into a text file and run on Windows. You do not need local admin rights to run this version.

Depending on the size of your registry and speed on your CPU, it may take up to one minute to run. The result is a message box with text that can be copied to the clipboard with Ctrl+C .

kevinarpe's user avatar

Another solution using PowerShell, this time leveraging .NET code (credit to jrich523.wordpress.com).

Plug this into a PowerShell console:

Produces output like this:

In Windows Explorer:

  1. Create a text file anywhere. e.g. temp.txt.
  2. Change the extension to "udl". E.g. temp.udl.
  3. Double click temp.udl.
  4. Go to the [Provider] Tab. Observe the list of "OLE

OLEDB provides a class that will enumerate all OLE DB providers for you.

  • ProgID: "MSDAENUM"
  • clsid:
  • CLSID_OLEDB_ENUMERATOR (from msdaguid.h in the sdk)

The steps

Create the enumerator

Get the results as an OLEDB IRowset :

The IRowset interface, like the rest of OLEDB is. merciless. It’s a nightmare of API, dreamed up in a time when Java was all the rage. Fortunately Microsoft created a friendly wrapper around OLEDB: called ActiveX Data Object (ADO). It even provides a handy function to wrap an OLEDB IRowset into an ADO Recordset (adapter pattern):

Now you can iterate the results:

SOURCES_NAME (0): The invariant name of the data store or enumerator.

SOURCES_PARSENAME (1): String to pass to IParseDisplayName to obtain a moniker for the data source object or enumerator.

SOURCES_DESCRIPTION (2): Description of the OLE DB data source object or enumerator.

SOURCES_TYPE (3): Specifies whether the row describes a data source object or an enumerator:

  • DBSOURCETYPE_DATASOURCE_TDP (1): Indicating a tabular data provider
  • DBSOURCETYPE_ENUMERATOR (2): Indicating an enumerator
  • DBSOURCETYPE_DATASOURCE_MDP (3): Indicating a multidimensional (OLAP) provider
  • DBSOURCETYPE_BINDER (4): Indicating a provider binder that supports direct URL binder If a single piece of code is capable of being used both as a data source object and as an enumerator, it is listed in the rowset twice, once in each role.

SOURCES_ISPARENT (4): If the row describes an enumerator, SOURCES_ISPARENT is VARIANT_TRUE if the enumerator is the parent enumerator; that is, the enumerator whose enumeration contains the enumerator on which ISourcesRowset::GetSourcesRowset was just called. This allows the consumer to go backward through the enumeration. Whether an enumerator is able to enumerate its parent is provider-specific. Otherwise, SOURCES_ISPARENT is VARIANT_FALSE.

If the row describes a data source object, SOURCES_ISPARENT is ignored by the consumer.

Ole db core services где находится

By default SQL Server listens on TCP port number 1433, and for named instances TCP port is dynamically configured. There are several options available to get the listening port for SQL Server Instance.

Here are a few methods which we can use to get this information.

Method 1: SQL Server Configuration Manager

Method 2: Windows Event Viewer

Method 3: SQL Server Error Logs

Method 4: sys.dm_exec_connections DMV

Method 5: Reading registry using xp_instance_regread

Let’s see how you can use each of these methods in detail:

Method 1: SQL Server Configuration Manager:

Step 1. Click Start > All Programs > Microsoft SQL Server 2012 > Configuration Tools > SQL Server Configuration Manager

Step 2. Go to SQL Server Configuration Manager > SQL Server Network Configuration > Protocols for <Instance Name>

Step 3. Right Click on TCP/IP and select Properties

Step 4. In TCP/IP Properties dialog box, go to IP Addresses tab and scroll down to IPAll group.

If SQL Server if configured to run on a static port it will be available in TCP Port textbox, and if it is configured on dynamic port then current port will be available in TCP Dynamic Ports textbox. Here my instance is listening on port number 61499.

Method 2: Windows Event Viewer:

When SQL Server is started it logs an event message as ‘Server is listening on [ ‘any’ <ipv4> <port number>’ in windows event logs. Here <port number> will be actual port number on which SQL Server is listening.

To view this using Event Viewer:

Step 1. Click Start > Administrative Tools > Event Viewer.

Note: If Administrative Tools are not available on Start menu, go to Start > Control Panel > System and Maintenance > Administrative Tools > View event logs

Step 2. Navigate to Event Viewer > Windows Logs > Application

Step 3. Since huge amount of event are logged, you need to use filtering to locate the required logs. Right click on Application and select Filter Current Log…

Step 4. You can filter the events by Event ID and Event source. The event we are interested in has Event ID of 26022, and it’s source is SQL Server Instance. You need to filter by both Event ID and SQL Server Instance if you have multiple instances installed, for a single instance you can filter by Event ID only. Click on OK to apply the filter.

Step 5. Once the filter is applied, Locate message ‘Server is listening on [ ‘any’ <ipv4> …’. As we can see from below screenshot that SQL Server Instance is running on TCP Port 61499.

Method 3: SQL Server Error Logs:

When SQL Server is started it also logs an message to SQL Server Error Logs. You can search for port number in SQL Server Error Logs by opening SQL Server Error Log in notepad or via T-SQL using extended stored procedure xp_ReadErrorLog as below:

EXEC xp_ReadErrorLog 0, 1, N’Server is listening on’, N’any’, NULL, NULL, ‘DESC’

LogDate ProcessInfo Text

2013-03-21 13:34:40.610 spid18s Server is listening on [ ‘any’ <ipv4> 61499].

2013-03-21 13:34:40.610 spid18s Server is listening on [ ‘any’ <ipv6> 61499].

(2 row(s) affected)

As we can see from the output that SQL Server Instance is listening on 61499.

Note: This method does not work if SQL Server Error Logs have been cycled. See sp_Cycle_ErrorLog for more information.

Method 4: sys.dm_exec_connections DMV:

DMVs return server state that can be used to monitor SQL Server Instance. We can use sys.dm_exec_connections DMV to identify the port number SQL Server Instance is listening on using below T-SQL code:

WHERE session_id = @@SPID

(1 row(s) affected)

As we can see from the output… same as above Smile

Method 5: Reading registry using xp_instance_regread:

Port number can also be retrieved from Windows Registry database.

We can use extended stored procedure xp_instance_regread to get port number information using below T-SQL code:

DECLARE @portNumber NVARCHAR(10)

‘Software\Microsoft\Microsoft SQL Server\MSSQLServer\SuperSocketNetLib\Tcp\IpAll’,

@value = @portNumber OUTPUT

SELECT [Port Number] = @portNumber

(1 row(s) affected)

As we can see … same as above Smile Smile

Note: The above code will only work if SQL Server is configured to use dynamic port number. If SQL Server is configured on a static port, we need to use @value_name = ‘TcpPort’ as opposed to @value_name = ‘TcpDynamicPorts’.

Hope This Helps!

Microsoft SQL Server может работать в двух режимах:
Прослушивание одного порта (по-умолчанию это TCP порт 1433). Этот режим будет выбран по-умолчанию, если во время установки SQL Server не использовать именованный экземпляр.
Динамический выбор портов. В этом случае при запуске SQL Server выберет свободный порт. Этот режим будет выбран по-умолчанию, если во время установки SQL Server настроить на использование именованного экземпляра.

Для того чтобы определить и изменить режим работы SQL Server нужно:
Открыть «Диспетчер конфигурации SQL Server»
В левом столбце выбрать «Сетевая конфигурация SQL Server» -> «Протоколы для <инстанция SQL Server>»
В правом столбце дважды кликнуть по протоколу TCP/IP
В открывшемся окне в разделе IPAll указано два параметра:
«TCP порт» — при помощи этого параметра можно задать статический порт. По-умолчанию значение 1433.
«Динамические TCP порты» — при помощи этого параметра можно задать диапазон, из которых будет выбираться порт для SQL Server

UDL files and connection strings

A co-worker showed me a really neat trick the other day. We deal with a lot of connection problems and one of the first places I look is the connection string. Now I’ve gotten pretty good at it over the years and more often than not I can point to problems. However, those other times can be a real pain. There is a great reference for connection strings but even it doesn’t always help. So what was the trick?

It turns out that udl files are mapped to something called OLE DB Core Services.

This neat little tool will let you test or create connection strings.

Create

I haven’t found a way to just open the tool but if you create a udl file and double click on it then it will open.

Читать:
Можно ли использовать моноблок как монитор

Currently, it’s blank, and the first step is to confirm the provider on the provider tab. I’m switching from the OLE DB provider for MS SQL to SQL Server Native Client 11.0.

Next fill in the server, login (trusted or SQL Id) and the initial database if any.

Last but not least you have the Advanced options (only the connection time in this case) and then you can hit Test Connection. Assuming it tests correctly you can now close the tool and open the udl file with a text editor. In this case here are the contents:

And you’ll see that line 3 of the file is the connection string. Of course, there are other ways to create connection strings but this is pretty handy.

Now, my favorite part of this is the ability to test them.

First, create a UDL file just like before and open it with a text editor. Here’s where things got weird. Those first two lines? I had to copy them exactly into the new file. I’m guessing there are other options here but I don’t know them and every letter had to be exact for this to work. Once that was done however I was able to put my connection string in with very limited information.

I save the file, then double click on it and the editor comes back up. And this time I was able to just hit the connection test button and confirm that it works! I can of course also make changes, test them and then look in the file to see the results.

SQL Server Integration Services (SSIS) для начинающих – часть 2

В этой части изменим логику загрузки справочника Products:

  1. При помощи компонента «Union All» объединим два входящих потока в один;
  2. Для новых записей будем делать вставку, а для записей, которые уже были добавлены ранее будем делать обновление. Для разделения записей на добавляемые и обновляемые воспользуемся компонентом Lookup;
  3. Для обновления записей применим компонент «OLE DB Command».

Итого в этой части мы познакомимся с четырьмя новыми компонентами: Union All, Lookup, OLE DB Command и Multicast.

Дальше так же будет очень много картинок.

Продолжим знакомство с SSIS

Создадим новый пакет:

И переименуем его в «LoadProducts_ver2.dtsx»:

В области «Control Flow» создадим «Data Flow Task»:

Двойным щелчком по элементу «Data Flow Task» зайдем в его область «Data Flow». Создадим два элемента «Source Assistant» для соединений SourceA и SourceB. Переименуем эти элементы в «Source A» и «Source B» соответственно:

«Source A» настроим следующим образом:

В целях демонстрации больших возможностей за раз, здесь я намеренно отпустил SourceID.

«Source B» настроим следующим образом:


Текст запроса:

В результате набор A у нас будет иметь 3 колонки [SourceProductID, Title, Price], а набор B будет иметь 4 колонки [SourceProductID, SourceID, Title, Price].

Воспользуемся элементом «Union All», чтобы объединить данные из 2-х наборов в один. Направим в него синие стрелки из «Source A» и «Source B»:

Каким образом делается сопоставление колонок двух входящих наборов, можно увидеть дважды щелкнув на элементе «Union All»:

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

В данном случае значения SourceID набора «Source A» будут равны NULL.

Для того чтобы заменить NULL значения на «A» воспользуемся компонентом «Derived Column» в который направим поток из «Union All»:

Двойным щелчком зайдем в редактор «Derived Column» и настроим его следующим образом:

Проделаем следующее (мышь в помощь):

  1. Укажем в «Derived Column» значение «Replace ‘SourceID’» — это будет означать что мы на выходе заменяем старую колонку SourceID на новую;
  2. Перетащим в область «Expression» функцию REPLACENULL;
  3. Перетащим на место первого аргумента функции REPLACENULL колонку SourceID;
  4. В качестве второго аргумента пропишем константу «A».

Теперь при запуске пакета на выполнение вы сможете увидеть набор, который получился в результате:


Здесь видно, что на этом этапе (до Derived Column) в колонке SourceID для строк первого набора стоят значения NULL.

Для того чтобы определить была ли добавлена ранее запись в базу DemoSSIS_Target воспользуемся компонентом Lookup:

Дважды щелкнув по нему настроим данный элемент:

Здесь мы скажем, что те строки, для которых не найдено соответствие, мы будем перенаправлять в поток «no match output». В этом случае на выходе мы получим 2 набора «Lookup Match Output» и «Lookup No Match Output».

«Full cache» говорит о том, что набор, который будет использоваться в качестве справочника одним SQL запросом (см.на следующей вкладке) будет полностью загружен в память и строки будут сопоставляться уже с кэша без повторных обращений к SQL Server.

На следующей вкладке нам нужно определить набор, который будет выступать в роли справочника:

Я прописал здесь запрос:

На следующей вкладке нужно указать по каким полям делается поиск строки в справочнике и какие колонки из справочника нужно добавить в выходной набор (если это нужно):

Для определение связи нужно при помощи мыши перетащить поле SourceProductID на SourceProductID и поле SourceID на SourceID.

Добавим компонент «Destination Assistant» для вставки записей с потока «Lookup No Match Output»:

Перетащим синюю стрелку с «Lookup» на «OLE DB Destination» и в диалоговом окне выберем поток «Lookup No Match Output»:

В итоге мы получим следующее:

Дважды щелкнув по «OLE DB Destination» настроим его:

Обработку вставки новых записей мы сделали.

Теперь для обновления ранее вставленных записей воспользуемся компонентом «OLE DB Command» и перенесем на него синюю стрелку от Lookup:

В этот компонент автоматически будет направлен поток «Lookup Match Output», т.к. поток «Lookup No Match Output» мы уже выбрали ранее:

Дважды щелкнем на «OLE DB Command» и настроим его:

Пропишем следующий запрос на обновление:

На следующей вкладке укажем каким образом будут задаваться параметры на основании данных строк входящего набора «Lookup Match Output»:

Через SSMS добавим новых продуктов в базу DemoSSIS_SourceB:

Для того чтобы отследить как менялись данные, вы можете, перед запуском пакета на выполнение, в необходимых местах сделать «Enable Data Viewer»:

Запустим пакет на выполнение:

В итоге мы должны увидеть, что 3 строки было вставлено при помощи компонента «OLE DB Destination» и 10 строк обновлено при помощи компонента «OLE DB Command».

Запрос прописанный в «OLE DB Command» выполнился для каждой строки входящего набора, т.е. в данном примере 10 раз.

В «OLE DB Command» можно прописать более сложную логику на TSQL, например, сделать проверку, были ли изменены Title или Price, и делать обновление соответствующей строки только если какое-то из значений отличается.

Для наглядности добавим новую колонку в таблицу Products в базе DemoSSIS_Target:

Давайте теперь пропишем следующую команду:

После чего переопределим привязку параметров согласно их очередности в тексте команды:

Сделаем в базе DemoSSIS_SourceA обновление:

И снова запустим проект на выполнение. В результате после очередного запуска пакета на выполнение, UPDATE должен будет выполниться только 1 раз, только для этой записи.

После выполнения пакета проверим это при помощи запроса:

В рамках данной части рассмотрим еще компонент «Multicast». Данный компонент позволяет получить из одного потока несколько. Это может быть полезно, когда одни и те же данные необходимо записать в два или более разных мест – т.е. входит один набор, а выходит столько его копий сколько нам нужно, и с каждой копией этого набора мы можем делать что захотим.

Для примера создадим в базе DemoSSIS_Target еще одну таблицу LastAddedProducts:

Для очистки этой таблицы добавим в область «Control Flow» компонент «Execute SQL Task» и пропишем в нем команду «TRUNCATE TABLE LastAddedProducts»:

Перейдем в область «Data Flow» компонента «Data Flow Task» и добавим компонент следующим образом:

Обратите внимание на желтый восклицательный знак – это произошло из-за того, что мы добавили колонку UpdatedOn и не привязали ее. Зайдем в элемент «OLE DB Destination», перейдем на вкладку Mappings оставим для колонки UpdatedOn в качестве входящего поля Ignore и нажмем OK:

Создадим еще один элемент «OLE DB Destination» и перетащим на него вторую синюю стрелку от элемента Multicast:

Переименуем для наглядности:

Настроим «To LastAddedProducts»:

Удалим через SSMS три последние вставленные записи:

И запустим пакет на выполнение:

В итоге добавление произошло в 2 таблицы – Products и LastAddedProducts.

Заключение по второй части

SSIS достаточно интересный инструмент, который на мой взгляд не помешает иметь в своем арсенале, так как в некоторых случаях он может сильно упростить процесс интеграции. Но конечно бывают ситуации, когда все взвесив, разумнее написать интеграцию прибегая к другим способам, например, использовать Linked Servers и писать процедуры на чистом TSQL или писать свою утилиту на каком-то другом языке программирования с применением всей мощи ООП и т.п.

Изучая материал проявляйте больше любопытства, например, щелкайте по вкладкам, которые я не показал, смотрите и анализируйте информацию на них, щелкайте по стрелкам, у них тоже есть свои свойства и настройки. Экспериментируйте, со всем что вам покажется интересным, не ленитесь делать свои небольшие тестовые примеры. Меняйте схему, так чтобы это приводило к исключениям, выбирайте более подходящие параметры у компонент пытаясь найти наиболее подходящий выход из сложившейся ситуации.

Похожие статьи