-->
Здесь я публикую небольшие мои заметки, а также интересные ссылки, все что связанно с моей профессией. Для перехода на персональный сайт, используйте ссылку http://k-semenenko.blogspot.com

четверг, 25 ноября 2010 г.

Использование Change Data Capture (CDC) in SQL Server 2008.

Пару дней назад на работе возникала необходимость в одном из проектов отслеживания изменений в базе данных. Задача такая: есть насколько таблиц, которые нужно мониторить на предмет операций Insert, update и delete. Сначала, решили исползовать аудит, но он не давал нам необходимой информации, такой как с какого на какое значение быль выполнен update или что именно было удалено и т.п. Поискав решения вспомнил о SQL Server СDC (Change Data Capture). Никогда раньше не использовал эту службу и вот что нарыл:

use SRPV
go

Активация CDC-функционала для конкретной  базы данных

exec sys.sp_cdc_enable_db

Ппроверяем что значение поля is_cdc_enabled в sys.databases изменилось для БД SRPV. Это признак того что для указанной БД активирована служба CDC.

select name, is_cdc_enabled from sys.databases

Активируем CDC для конкретной таблицы (в данном примере это таблица WaggonsSend). Будет созданно 2 job-а. cdc.test_new_capture и cdc.test_new_cleanup
Для добавления таблицы указываем ее имя в @source_name.

exec sys.sp_cdc_enable_table
    @source_schema = 'dbo',
    @source_name = 'WaggonsSend' ,
    @role_name = 'CDC_Admins',
    @supports_net_changes = 1

Проверяем  таблица установлена источником СDC
 
select name, type, type_desc, is_tracked_by_cdc, * from sys.tables
where name in ('dbo_WaggonsSend')

Просмотр всех объектов созданных для обеспечения функционирования CDC.

select o.name, o.type, o.type_desc, s.name from sys.objects o
join sys.schemas  s on s.schema_id = o.schema_id
where s.name = 'cdc'

Просмотр изменений в таблице можно просмотреть так:

use SRPV
DECLARE @begin_lsn binary(10), @end_lsn binary(10)
SET @begin_lsn = sys.fn_cdc_get_min_lsn('dbo_WaggonsSend')
SET @end_lsn   = sys.fn_cdc_get_max_lsn()
select tm.tran_begin_time,
        tm.tran_end_time,
        tm.tran_id,
    CASE __$operation
     when 1 then  'delete'
      when 2 then  'insert'
     when 3 then  'update (before the update)'
     when 4 then  'update (after the update)'
    end operation,
    ch.*
from cdc.fn_cdc_get_all_changes_dbo_WaggonsSend(@begin_lsn, @end_lsn, 'all update old') ch
left join cdc.lsn_time_mapping tm on ch.__$start_lsn=tm.start_lsn

Просмотр джобов отвечающих за работу CDC (здесь можно просмотреть такие параметры как
pllinginterval - с какой периодичностью в сек. движок будет сканировать транзакшн лог и заполнять хранилище информации
retention - количество минут сколько будет храниться инфа в хранилище. Отчисткой занимается джоб cdc.test_new_cleanup, запускаемый 1 разв неделю)

use msdb
select * from dbo.cdc_jobs

Редактирование этих параметроов

EXEC [sys].[sp_cdc_change_job]
    @job_type = N'capture',
    @pollinginterval = 5  --раз в пять секунд движок CDC будет сканировать транзакшн лог и пополнять хранилище информацией. Делается это джобом cdc.test_new_capture, который запущен всегда, т.е. один раз запущен и находится в статусе Running постоянно.

EXEC [sys].[sp_cdc_change_job]
    @job_type = N'cleanup',
    @retention = 10080 --  10080 минут - это 7 дней. Именно столько я установил для хранения истории в хранилище.


Просмотр всех таблиц на которых сконфигурированна CDC в текущей БД
EXECUTE sys.sp_cdc_help_change_data_capture;


Хранилище это системные таблицы, созданные в процессе конфигурирования CDC. Информацию из можно селектить как с помощью хп cdc.fn_cdc_get_all_changes_dbo_WaggonsSend (синтаксис я указывал выше) так и напрямую

 select * from cdc.dbo_WaggonsSend_CT
where bla-bla-bla

А здесь подробнейшая информация на эту тему =))

суббота, 20 ноября 2010 г.

Экзамены по новой версии SQL Server code-named Denali

Экзамены по новой версии SQL Server code-named Denali: "

По новой версии SQL Server 'Denali' планируются к выпуску следующие экзамены:


70-460 PRO: Designing, Optimizing and Maintaining a Database Administrative Solution Using Microsoft SQL Server 11
70-461 PRO: Designing Database Solutions and Data Access Using Microsoft SQL Server 11
70-586 TS: Microsoft SQL Server 11, Implementation and Maintenance
70-587 TS: Microsoft® SQL Server 11, Database Development
70-588 TS: Microsoft SQL Server 11, Business Intelligence Development and Maintenance


Post from: http://shomin.info

Экзамены по новой версии SQL Server code-named Denali




Related posts:

  1. SQL Server code-named “Denali” Выпущен CTP1 новой версии SQL Server - “Denali”. Подробности здесь: code-named “Denali” web page CTP Books Online Post from: http://shomin.infoSQL Server code-named “Denali”...

  2. SQL Server 2005 Подробности смотрите в моей публикации Курсы SQL Server 2005 – что выбрать?   MCTS: SQL Server 2005 Требования: Экзамен 70-431 TS: Microsoft SQL Server 2005 - Implementation and Maintenance Курсы для подготовки: Курс 2778: Writing Queries Using Microsoft SQL Server 2008 Transact-SQL (3 дня) (этот курс рассчитан на обе версии...

  3. Экзамены по Visual Studio 2010 Начато создание экзаменов по Visual Studio 2010. Планируются к выпуску следующие экзамены: 70-511 TS: Microsoft .NET Framework 4, Windows Applications Development (WPF) 70-515 TS: Microsoft .NET Framework 4, Web Applications Development 70-513 TS: Microsoft .NET Framework 4, Windows Communication Foundation Development 70-516 TS: Microsoft .NET Framework 4, Accessing Data with...

"

среда, 10 ноября 2010 г.

Мелкая, но приятная фича SQL Server Denali - Sequence numbers!

Новая версия SQL Server-а дает возможность заюзать нам SEQUENCE NUMBERS- генерация последовательных значений и на всегда забыть чтото типа NextID или GenID или identity полей. Приятного чтения =)) http://msdn.microsoft.com/en-us/library/ff878058%28v=SQL.110%29.aspx

--
BR Semenenko Konstantin

Вышла CTP версия нового SQL Server Denali и SQL Server 2008 R2 Parallel Data Warehouse.

Что нового в  SQL Server Denali CTP относительно R2?  (статья на русском http://www.gotdotnet.ru/blogs/DeColores/8895/ 


Что такое SQL Server 2008 R2 Parallel Data Warehouse - http://blogs.technet.com/b/dataplatforminsider/archive/2010/11/09/parallel-data-warehouse-is-now-available.aspx
--
BR Semenenko Konstantin

суббота, 23 октября 2010 г.

SQL SERVER – Taking Multiple Backup of Database in Single Command – Mirrored Database Backup

SQL SERVER – Taking Multiple Backup of Database in Single Command – Mirrored Database Backup: "

I recently had a very interesting experience. In one of my recent consultancy works, I was told by our client that they are going to take the backup of the database and will also a copy of it at the same time. I expressed that it was surely possible if they were going to use a mirror command. In addition, they told me that whenever they take two copies of the database, the size of the database, is always reduced. Now this was something not clear to me, I said it was not possible and so I asked them to show me the script.


Here was their script:


BACKUP DATABASE [AdventureWorks] TO

DISK =
N'D:\AdventureWorks.bak'

, DISK = N'E:\AdventureWorks.bak'

WITH FORMAT, INIT,

NAME = N'AdventureWorks-Full Database Backup'

GO


This script was very interesting to me. There is nothing wrong with it; however it does not duplicate your data. In fact, it splits your backup file in two parts and, when you restore, you will need both of these files. This was the reason why the size of the backup file was reduced whenever they took a backup on two places.


What they really needed was the following script wherein the full backup would be mirrored to another backup location:


BACKUP DATABASE [AdventureWorks] TO

DISK =
N'D:\AdventureWorks.bak'

MIRROR TO DISK = N'E:\AdventureWorks.bak'

WITH FORMAT, INIT,

NAME = N'AdventureWorks-Full Database Backup'

GO


In this case, when you check the size of the backup, you will notice that its size is not reduced as well.


I have previously written on this subject in very much detail. Here is the in-depth article about the same topic:


SQL SERVER – Mirrored Backup and Restore and Split File Backup


Do you use this MIRROR TO command in your production environment?


Reference : Pinal Dave (http://blog.sqlauthority.com)



Filed under: Pinal Dave, SQL, SQL Authority, SQL Backup and Restore, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, T SQL, Technology "

пятница, 22 октября 2010 г.

SQL SERVER – World Shapefile Download and Upload to Database – Spatial Database

SQL SERVER – World Shapefile Download and Upload to Database – Spatial Database: "

During my recent, training I was asked by a student if I know a place where he can download spatial files for all the countries around the world, as well as if there is a way to upload shape files to a database. Here is a quick tutorial for it.


VDS Technologies has all the spatial files for every location for free. You can download the spatial file from here. If you cannot find the spatial file you are looking for, please leave a comment here, and I will send you the necessary details. Unzip the file to a folder and it will have the following content.



Then, download Shape2SQL tool from SharpGIS. This is one of the best tools available to convert shapefiles to SQL tables. Afterwards, run the .exe file.


When the file is run for the first time, it will ask for the database properties. Provide your database details.



Select the appropriate shape files and the tool will fill up the essential details automatically. If you do not want to create the index on the column, uncheck the box beside it. The screenshot below is simply explains the procedure. You also have to be careful regarding your data, whether that is GEOMETRY or GEOGRAPHY. In this example,  it is GEOMETRY data.


Click “Upload to Database”. It will show you the uploading process. Once the shape file is uploaded, close the application and open SQL Server Management Studio (SSMS).




Run the following code in SSMS Query Editor.


USE Spatial

GO

SELECT *

FROM dbo.world

GO


This will show the complete map of world after you click on Spatial Results in Spatial Tab.




In Spatial Results Set, the Zoom feature is available. From the Select label column, choose the country name in order to show the country name overlaying the country borders.



Let me know if this tutorial is helpful enough. I am planning to write a few more posts about this later.


Note: Please note that the images displayed here do not reflect the original political boundaries. These data are pretty old and can probably draw incorrect maps as well. I have personally spotted several parts of the map where some countries are located a little bit inaccurately.


Reference : Pinal Dave (http://blog.SQLAuthority.com)



Filed under: Pinal Dave, SQL, SQL Add-On, SQL Authority, SQL Query, SQL Scripts, SQL Server, SQL Spatial, SQL Tips and Tricks, SQL Utility, T SQL, Technology "

Investigating Transactions Using Dynamic Management Objects

very good article about transactions in SQL Server

http://www.simple-talk.com/sql/database-administration/investigating-transactions-using-dynamic-management-objects/

вторник, 21 сентября 2010 г.

fn_fixeddrives() : an alternative for xp_fixeddrives

xp_fixeddrives на дает нам полной информации о состоянии дисковой подсистемы на сервере. Раньше приходилось совместно с этим использовать утилиту windows  fsutil volume diskfree чтобы получить полный объем дисков. Интересное решение предлагается  на sqlservercentral. возьмем на вооружение =)))
http://www.sqlservercentral.com/articles/SQLCLR/70963/

--
BR Semenenko Konstantin

четверг, 2 сентября 2010 г.

Как просмотреть текущие значения параметров сессий SQL Server.

Source http://www.mssqltips.com/tip.asp?tip=1415

Problem

With each session that is made to SQL Server the user can configure the options that are SET for that session and therefore affect the outcome of how queries are executed and the underlying behavior of SQL Server.  Some of these options can be made via the GUI, while others need to be made by using the SET command.  When using the GUI it is easy to see which options are on and which options are off, but how can you get a better handle on all the options that are currently set for the current session?

.
Value Configuration Description
1 DISABLE_DEF_CNST_CHK Controls interim or deferred constraint checking.
2 IMPLICIT_TRANSACTIONS For dblib network library connections, controls whether a transaction is started implicitly when a statement is executed. The IMPLICIT_TRANSACTIONS setting has no effect on ODBC or OLEDB connections.
4 CURSOR_CLOSE_ON_COMMIT Controls behavior of cursors after a commit operation has been performed.
8 ANSI_WARNINGS Controls truncation and NULL in aggregate warnings.
16 ANSI_PADDING Controls padding of fixed-length variables.
32 ANSI_NULLS Controls NULL handling when using equality operators.
64 ARITHABORT Terminates a query when an overflow or divide-by-zero error occurs during query execution.
128 ARITHIGNORE Returns NULL when an overflow or divide-by-zero error occurs during a query.
256 QUOTED_IDENTIFIER Differentiates between single and double quotation marks when evaluating an expression.
512 NOCOUNT Turns off the message returned at the end of each statement that states how many rows were affected.
1024 ANSI_NULL_DFLT_ON Alters the session's behavior to use ANSI compatibility for nullability. New columns defined without explicit nullability are defined to allow nulls.
2048 ANSI_NULL_DFLT_OFF Alters the session's behavior not to use ANSI compatibility for nullability. New columns defined without explicit nullability do not allow nulls.
4096 CONCAT_NULL_YIELDS_NULL Returns NULL when concatenating a NULL value with a string.
8192 NUMERIC_ROUNDABORT Generates an error when a loss of precision occurs in an expression.
16384 XACT_ABORT Rolls back a transaction if a Transact-SQL statement raises a run-time error.

(Source: SQL Server 2005 Books Online)

In a previous tip, Reproducing Query Execution Plan Performance Problems the author talked about how SET options could impact the outcome of queries and performance issues, so this command could become useful to determine what the current options are for the session.

To get the settings for the current session you can run this simple SELECT statement:

SELECT @@OPTIONS

When run, this command returns an integer that represents the bit values as shown in the table above.

To help make further sense of these values you can run the following bitwise code that will show you what SET options are turned on.

DECLARE @options INT

SELECT @options = @@OPTIONS

PRINT @options
IF ( (1 & @options) = 1 ) PRINT 'DISABLE_DEF_CNST_CHK'
IF ( (2 & @options) = 2 ) PRINT 'IMPLICIT_TRANSACTIONS'
IF ( (4 & @options) = 4 ) PRINT 'CURSOR_CLOSE_ON_COMMIT'
IF ( (8 & @options) = 8 ) PRINT 'ANSI_WARNINGS'
IF ( (16 & @options) = 16 ) PRINT 'ANSI_PADDING'
IF ( (32 & @options) = 32 ) PRINT 'ANSI_NULLS'
IF ( (64 & @options) = 64 ) PRINT 'ARITHABORT'
IF ( (128 & @options) = 128 ) PRINT 'ARITHIGNORE'
IF ( (256 & @options) = 256 ) PRINT 'QUOTED_IDENTIFIER'
IF ( (512 & @options) = 512 ) PRINT 'NOCOUNT'
IF ( (1024 & @options) = 1024 ) PRINT 'ANSI_NULL_DFLT_ON'
IF ( (2048 & @options) = 2048 ) PRINT 'ANSI_NULL_DFLT_OFF'
IF ( (4096 & @options) = 4096 ) PRINT 'CONCAT_NULL_YIELDS_NULL'
IF ( (8192 & @options) = 8192 ) PRINT 'NUMERIC_ROUNDABORT'
IF ( (16384 & @options) = 16384 ) PRINT 'XACT_ABORT'

When the above code is run for my session, this is the output:

The first value 5496 displays the current @@OPTIONS value and the following lines signify which options are currently set for the session.

To illustrate how this value changes we are going to run SET NOCOUNT ON which should turn on bit value 512.  If we add 5496 and 512 the new value should be 6008.

SET NOCOUNT ON

DECLARE @options INT

SELECT @options = @@OPTIONS

PRINT @options
IF ( (1 & @options) = 1 ) PRINT 'DISABLE_DEF_CNST_CHK'
IF ( (2 & @options) = 2 ) PRINT 'IMPLICIT_TRANSACTIONS'
IF ( (4 & @options) = 4 ) PRINT 'CURSOR_CLOSE_ON_COMMIT'
IF ( (8 & @options) = 8 ) PRINT 'ANSI_WARNINGS'
IF ( (16 & @options) = 16 ) PRINT 'ANSI_PADDING'
IF ( (32 & @options) = 32 ) PRINT 'ANSI_NULLS'
IF ( (64 & @options) = 64 ) PRINT 'ARITHABORT'
IF ( (128 & @options) = 128 ) PRINT 'ARITHIGNORE'
IF ( (256 & @options) = 256 ) PRINT 'QUOTED_IDENTIFIER'
IF ( (512 & @options) = 512 ) PRINT 'NOCOUNT'
IF ( (1024 & @options) = 1024 ) PRINT 'ANSI_NULL_DFLT_ON'
IF ( (2048 & @options) = 2048 ) PRINT 'ANSI_NULL_DFLT_OFF'
IF ( (4096 & @options) = 4096 ) PRINT 'CONCAT_NULL_YIELDS_NULL'
IF ( (8192 & @options) = 8192 ) PRINT 'NUMERIC_ROUNDABORT'
IF ( (16384 & @options) = 16384 ) PRINT 'XACT_ABORT'

When the above code is run, this is the output with NOCOUNT now on:

Here is one more example where we have set NOCOUNT ON and QUOTED_IDENTIFIER OFF.

SET NOCOUNT ON
SET QUOTED_IDENTIFIER OFF

DECLARE @options INT

SELECT @options = @@OPTIONS

PRINT @options
IF ( (1 & @options) = 1 ) PRINT 'DISABLE_DEF_CNST_CHK'
IF ( (2 & @options) = 2 ) PRINT 'IMPLICIT_TRANSACTIONS'
IF ( (4 & @options) = 4 ) PRINT 'CURSOR_CLOSE_ON_COMMIT'
IF ( (8 & @options) = 8 ) PRINT 'ANSI_WARNINGS'
IF ( (16 & @options) = 16 ) PRINT 'ANSI_PADDING'
IF ( (32 & @options) = 32 ) PRINT 'ANSI_NULLS'
IF ( (64 & @options) = 64 ) PRINT 'ARITHABORT'
IF ( (128 & @options) = 128 ) PRINT 'ARITHIGNORE'
IF ( (256 & @options) = 256 ) PRINT 'QUOTED_IDENTIFIER'
IF ( (512 & @options) = 512 ) PRINT 'NOCOUNT'
IF ( (1024 & @options) = 1024 ) PRINT 'ANSI_NULL_DFLT_ON'
IF ( (2048 & @options) = 2048 ) PRINT 'ANSI_NULL_DFLT_OFF'
IF ( (4096 & @options) = 4096 ) PRINT 'CONCAT_NULL_YIELDS_NULL'
IF ( (8192 & @options) = 8192 ) PRINT 'NUMERIC_ROUNDABORT'
IF ( (16384 & @options) = 16384 ) PRINT 'XACT_ABORT'

When the above code is run, this is the output we get

 

Summary
This is a simple function that can give you a lot of insight into your current session settings.  By using this function, you can determine what settings users have set for their session and then determine if you need to turn certain options on or off to ensure your code acts as desired.



пятница, 30 июля 2010 г.

С днем сисамина!!!!

Последняя пятница июля – особенный день для системного администратора. Или, во всяком случае, должен быть особенным. Потому что этот день считается профессиональным праздником - международным днем системного администратора, хотя, возможно, не все профессионалы о нем знают. Поздравлять в этот день можно не только сисадминов, но и вебмастеров, администраторов телефонных станций, администраторов баз данных и почтовых серверов, а также системных программистов. В общем и целом, это те люди, которые «не дают колесам фирмы остановиться»

С праздником сисадмина

среда, 21 июля 2010 г.

Установка SQL Server 2008 R2. Что такое Slipstream?

Очень полезная статья о установке SQL Server 2008 R2. Описано понятие Slipstream, даны подробная инструкция по пропатчиванию дистрибутива.

В конце статьи также полезная инфа как при помощи инструкций, сохранённых в файле конфигурации установки, вы можете устанавливать SQL Server  в одинаковой конфигурации на нескольких машинах.
Ссылка на статью http://itband.ru/2010/07/install-microsoft-sql-server-2008-r2/

пятница, 16 июля 2010 г.

Tech·Ed North America 2010

 Tech·Ed is a great opportunity to network with thousands of your IT peers and get the latest information on Microsoft technologies, tools, and services. We will also have on-site certification testing. Visit our website for all the details, and delve into our session catalog.
http://northamerica.msteched.com/?fbid=cc-69E6G40H

Рождение моего профессионального блога.

Это место где я буду централизованно хранить информацию связанную с моей профессиональной деятельностью. Это не коммерческий какой-то сайт, и плагиатить тут тоже не собираюсь. В случае публикации какой либо статьи (если это не запрещено правообладателями), обязательно будет публиковаться ссылка на первоисточник.  Блог для личного пользования, но и не закрыт для остальных, чьи интересы схожи с моими. На сей ноте я приступаю к ведению своего профессионального блога. Кстати, мой другой Персональный блог ведется уже второй месяц и находится тут.....