- create procedure sp_enable_disable_cdc_all_tables(@dbname varchar(100), @enable bit)
- as
- BEGIN TRY
- DECLARE @source_name varchar(400);
- declare @sql varchar(1000)
- DECLARE the_cursor CURSOR FAST_FORWARD FOR
- SELECT table_name
- FROM INFORMATION_SCHEMA.TABLES where TABLE_CATALOG=@dbname and table_schema='dbo' and table_name != 'systranschemas'
- OPEN the_cursor
- FETCH NEXT FROM the_cursor INTO @source_name
- WHILE @@FETCH_STATUS = 0
- BEGIN
- if @enable = 1
- set @sql =' Use '+ @dbname+ ';EXEC sys.sp_cdc_enable_table
- @source_schema = N''dbo'',@source_name = '+@source_name+'
- , @role_name = N'''+'dbo'+''''
- else
- set @sql =' Use '+ @dbname+ ';EXEC sys.sp_cdc_disable_table
- @source_schema = N''dbo'',@source_name = '+@source_name+', @capture_instance =''all'''
- exec(@sql)
- FETCH NEXT FROM the_cursor INTO @source_name
- END
- CLOSE the_cursor
- DEALLOCATE the_cursor
- SELECT 'Successful'
- END TRY
- BEGIN CATCH
- CLOSE the_cursor
- DEALLOCATE the_cursor
- SELECT
- ERROR_NUMBER() AS ErrorNumber
- ,ERROR_MESSAGE() AS ErrorMessage;
- END CATCH
Wednesday, 24 February 2016
SQL Server Query for Enabling Change Data Capture On All Tables
Introduction To CDC (Change Data Capture) Of SQL Server - Part One
In this article, we will look intoa SQL Server feature, called CDC, used for tracking/auditing database changes at table level. This feature will help us to track database changes like INSERT, UPDATE and DELETE on tables.
It even tracks old and new values for an update operation. CDC uses SQL Server transaction logs for capturing all inserts, updates, and deletes on a table. This feature is available on 2008 or higher versions and part of enterprise editions. Let’s open management studio and enable CDC on EmployeeDB to track the changes by following the below steps:
Enable CDC on a database by running the following command, it needs sysadmin privileges.
Create a role to which we will give access to CDC tables (which will hold all data changes) using the following command:
It even tracks old and new values for an update operation. CDC uses SQL Server transaction logs for capturing all inserts, updates, and deletes on a table. This feature is available on 2008 or higher versions and part of enterprise editions. Let’s open management studio and enable CDC on EmployeeDB to track the changes by following the below steps:
Enable CDC on a database by running the following command, it needs sysadmin privileges.
Create a role to which we will give access to CDC tables (which will hold all data changes) using the following command:
- CREATEROLEcdc_role
- EXECsys.sp_cdc_enable_table
- @source_schema='dbo',-- Schema name
- @source_name='employees',-- Table Name
- @role_name=N'cdc_role'-- Role having access on CDC tables [having data audit details]
Let’s test CDC by doing some changes to employees table:
Let’s query our tracking table [dbo_employees_CT]:
If column _$operation is 1 it means it’s a DELETE operation; 2 means INSERT; 3 means Value before UPDATE; and 4 means Values after UPDATE. We will write the following query to get results more meaningfully:
Apart from dbo_employees_CT table, we have other tables created by CDC under System Tables to store metadata for its tracking purpose. Let’s understand purpose of each:
Captured_columns: It has all column’s details on which CDC is enabled:
Change_tables: It contains capture details like table name, role name etc along start and end lsn. Any change on a table is uniquely identified by LSN (log sequence number).
ddl_history: It contains information on any schema changes on the tracking table [employees] like adding\removing a column. Here, I added a new column location.
index_columns: It contains index details of tables on which tracking is enabled.
lsn_time_mapping: It contains mapping details of table change’s LSN and its time of occurrence:
I am ending things here. In next article, we will drill down more on CDC. I hope this article will be helpful for all.
Two options to store user friendly column names in SQL Server
Problem
Report-writing often involves putting labels on columns for easy recognition by the end users. Sometimes these labels change as the business changes and different users adopt the system. Are there any easy ways to automate displaying user-friendly column names with a minimum amount of rework in reports? Check out this tip to learn more.Solution
This article will review two approaches to storing user-friendly output in SQL Server itself. The first option that will be outlined is using SQL Server Extended Properties. The second option is using SQL Server Views.SQL Server Extended Properties
SQL Server allows classes of documentation to be written into the database. See Using Extended Properties on Database Objects for the complete list. This tip will focus on columns and tables for use with user-readable output.Starting with the basics, below is a script that creates a database, table and adds two column captions.
Extended Property creation code
|
---|
use master go if db_id('SQLTips_UFOutput') > 0 drop database SQLTips_UFOutput go create database SQLTips_UFOutput go use SQLTips_UFOutput go create table person ( pers_id int identity(1,10) not null, pers_fname varchar(50) not null, pers_ssn varchar(12) not null, constraint PK_pers primary key (pers_id) ) insert into person values ('John', '123-45-6789'), ('Luke', '987-00-1249'), ('Janet', '232-34-3208') EXEC sp_addextendedproperty @name = N'Caption', @value = 'First name', @level0type = N'Schema', @level0name = dbo, @level1type = N'Table', @level1name = person, @level2type = N'Column', @level2name = pers_fname; GO EXEC sp_addextendedproperty @name = N'Caption', @value = 'Social Security number', @level0type = N'Schema', @level0name = dbo, @level1type = N'Table', @level1name = person, @level2type = N'Column', @level2name = pers_ssn; GO |
Confirm the text is saved by calling a function with parameter values that drill down to the table.
Extended Property retrieval code
|
---|
select * from fn_listextendedproperty( 'caption', N'schema', 'dbo', N'table', 'person', N'column', default ) |
Extended Property integration into result set
|
---|
declare @dynSQL nvarchar(4000), -- SQL command the run built using the captions @colName varchar(50), -- SQL column name @colAlias varchar(50), -- Caption defined as an extendedproperty @comma bit -- flag used for proper SQL string-building declare colAlias cursor for select cast(exprop.objname as varchar), cast(exprop.value as varchar) from fn_listextendedproperty( 'caption', N'schema', 'dbo', N'table', 'person', 'column', default ) exprop -- if every column has an extended property; scroll down for a left join example inner join sys.columns syscol on cast(exprop.objname as varchar) collate SQL_Latin1_General_CP1_CI_AS = cast(syscol.name as varchar) collate SQL_Latin1_General_CP1_CI_AS -- these casts are explained below -- initialize output string set @dynSQL = 'select ' set @comma = 0 -- output each column name and alias open colAlias fetch from colAlias into @colName, @colAlias while @@fetch_status = 0 begin if @comma = 1 set @dynSQL = @dynSQL + ', ' set @dynSQL = @dynSQL + quotename(@colName) + ' as ' + quotename(@colAlias) set @comma = 1 fetch next from colAlias into @colName, @colAlias end close colAlias deallocate colAlias set @dynSQL = @dynSQL + ' from person' exec sp_executeSQL @dynSQL |
Results of dynamic SQL above
|
---|
select [pers_fname] as [First name], [pers_ssn] as [Social Security number] from person |
So why are there so many casts in the code above? They are used in response to this error message: Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AI" in the equal to operation. Good thing we're skilled mediators.
The above could be taken one step further to have the statement which writes the text "person" as a parameter and table name dynamic-generated as well. That would be all that's needed for user-friendly output once the captions have been added to tables.
Adding captions to every table seems redundant in cases where columns are fine as they are. This query uses a caption if there is one, otherwise the column name:
Retrieving Extended Properties or their column names when no captions exist
|
---|
select coalesce(cast(exprop.objname as varchar) collate SQL_Latin1_General_CP1_CI_AS, syscol.name) as colname, coalesce(cast(exprop.value as varchar) collate SQL_Latin1_General_CP1_CI_AS, syscol.name) as colalias from sys.columns syscol left outer join fn_listextendedproperty( 'caption', N'schema', 'dbo', N'table', 'person', 'column', default ) exprop on cast(exprop.objname as varchar) collate SQL_Latin1_General_CP1_CI_AS = cast(syscol.name as varchar) collate SQL_Latin1_General_CP1_CI_AS where syscol.object_id = object_id('person') |
Here are a few notes on this code:
- The source table is sys.columns which may include unneeded columns in the report.
- The coalesces simply pick the first non-null value, and because all data types in its invocation need to be the same, that 43-character cast in needed.
- To use this query, simply replace the above cursor query with it.
Extended Properties updating
|
---|
exec sp_updateextendedproperty @name = N'Caption', @value = 'Social Security #', @level0type = N'Schema', @level0name = dbo, @level1type = N'Table', @level1name = person, @level2type = N'Column',@level2name = pers_ssn; GO |
Extended Properties deleting
|
---|
exec sp_dropextendedproperty @name = N'Caption', @level0type = N'Schema', @level0name = dbo, @level1type = N'Table', @level1name = person, @level2type = N'Column',@level2name = pers_ssn; GO |
Extended Properties creation for a table
|
---|
EXEC sp_addextendedproperty @name = N'Caption', @value = 'Company Personnel', @level0type = N'Schema', @level0name = dbo, @level1type = N'Table', @level1name = person; GO select * from fn_listextendedproperty(null, N'schema', 'dbo', N'table', 'person', default, default) |
I applaud anyone that has read this far as that is an amount of code that may need cut down to reach production given the pace of organization and level of commitment to documentation. This next method recreates the ability to have user-friendly column names with far less typing.
Views
If there's only an interest in column or table aliasing, it's also possible to use views as opposed to the extended properties, without as much overhead. Here is an example:
View creation for user-friendly columns
|
---|
create view vuf_person as -- vuf = view user-friendly select pers_fname as [First name], pers_ssn as [Social Security number] from person go select * from vuf_person |
View updating for user-friendly columns
|
---|
alter view vuf_person as select pers_fname as [First name], pers_ssn as [Social Security #] from person go select * from vuf_person |
View creation for user-friendly table names
|
---|
create view [Personnel Report] as select pers_fname as [First name], pers_ssn as [Social Security #] from person go select * from [Personnel Report] |
Next Steps
- Decide what level of documentation to store in the database
- If only column- and table-level captions are needed, the view option is possible and requires less code
- Consider isolating new tables with user-friendly views that use human-readable aliases
- Use those views in SSRS and enjoy how the column names are user-friendly without any work
- Create an interface for users to allow updating the view column aliases that uses a dynamically-generated ALTER VIEW statement
- Read more about sp_addextendedproperty, sp_updateextendedproperty, sp_deleteextendedproperty and the complete list of extended properties
- Be creative. What else could these captions be used for? How else could they be organized? Are there any other extended properties that seem useful in your environment?
Tuesday, 2 February 2016
Start With AngularJS: Part 7
Thank you for reading my previous articles. If you have not read
them, then study from the following links. After reading them it will be
easier to understand today’s topics.
It helps us to divide your app into multiple view and bind it different views to Controllers. A route is specified in the URL after the # sign.
Like:
$ rout Provider taken care by AngularJS. To define the routes for your app$route Provider service provides method when () and otherwise ().
Example:
AngularJS Events
That directive allows you to run its functions at user event. It is not overwriting with HTML5 event. In page both events can be executed at a time.
It has several types:
Output
I hope you will understand and will practice with my demo.
- Overview Of AngularJS: Part 1
- Start With AngularJS: Part 2
- Start With AngularJS: Part 3
- Start Up With AngularJS Part: 4
- Start With AngularJS: Part 5
- Start With AngularJS: Part 6
It helps us to divide your app into multiple view and bind it different views to Controllers. A route is specified in the URL after the # sign.
Like:
$ rout Provider taken care by AngularJS. To define the routes for your app$route Provider service provides method when () and otherwise ().
Example:
- var sampleApp = angular.module('sampleApp', []);
- sampleApp.config(['$routeProvider',
- function($routeProvider)
- {
- $routeProvider.
- when('/ShowOrder/:orderId',
- {
- templateUrl: 'templates/show_order.html',
- controller: 'ShowOrderController'
- });
- }
- ]);
- sampleApp.controller('ShowOrderController', function($scope, $routeParams)
- {
- $scope.order_id = $routeParams.orderId;
- });
That directive allows you to run its functions at user event. It is not overwriting with HTML5 event. In page both events can be executed at a time.
It has several types:
- Ng-Mouse enters: it execute of mouse when itenter on element area.
- Ng-mouse over: it execute of mouse when it over on element area.
- Ng-mouse move: it execute of mouse when it move on element area.
- Ng-mouse leave: it execute of mouse when it leave on element area.
- Ng-mouse down: it execute of mouse when it down on element area.
- Ng-mouse up: it execute of mouse when it up on element area.
- Ng-click: it execute when click on element area.
- Ng-change: it execute when changed on element area.
- Ng-key press: After key press that event execute.
- Ng-Submit: it execute of mouse click on element area.
- Ng-blur: it execute after blur on element area.
- Ng-copy: it execute after copy text on element area.
- Ng-cut: it execute after cut text on element area.
- Ng-dblclick: it execute after dbl click on element area.
- Ng-focus: it execute after focusing on element area.
- Ng-paste: it execute after paste on element area.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Event Demo</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
- </script>
- </head>
- <body>
- <h3> Angular JS change Events</h3>
- <br/>
- <script>
- var app = angular.module("app", []);
- app.controller("ChangeController", function($scope)
- {
- $scope.CheckBoxChanged = function()
- {
- $scope.CheckBoxStatus = $scope.chkValue;
- };
- $scope.KeyDown = function()
- {
- $scope.keydown = " Key down executes " + new Date().getTime();
- }
- $scope.TextBoxChanged = function()
- {
- $scope.TextBoxStatus = $scope.txtValue;
- };
- $scope.KeyPress = function()
- {
- $scope.keypress = " Key press executes " + new Date().getTime();
- }
- $scope.DropDownChnaged = function()
- {
- $scope.DropDownStatus = $scope.dropValue;
- };
- });
- </script>
- <div ng-app="app" ng-controller="ChangeController">
- <input type="checkbox" name="chk1" ng-model="chkValue" ng-change="CheckBoxChanged()" />
- <p>Check box status: {{ CheckBoxStatus }}</p>
- <br/>
- <inputtype="text" name="txt1" ng-model="txtValue" ng-change="TextBoxChanged()" />
- <p>Text box status: {{ TextBoxStatus }}</p>
- <input type="text" ng-keydown="KeyDown()" ng-keypress="KeyPress()" ng-keyup="KeyUp()" />
- <br/>
- <p>Key down - {{ keydown }}</p>
- <p>Key press - {{ keypress }}</p>
- <br/>
- <select name="dropChange" ng-model="dropValue" ng-change="DropDownChnaged()">
- <option value="Male">Male</option>
- <option value="Female">Female</option>
- </select>
- <p>Dropdown box status: {{ DropDownStatus }}</p>
- </div>
- </body>
- </html>
- <!DOCTYPE html>
- <html>
I hope you will understand and will practice with my demo.
Monday, 1 February 2016
Start With AngularJS: Part 6
Thank you for reading my previous article. If you have not read that,
then study from the following links. After reading them it would be
easier to understand today’s topics.
What is a Service
Services are JavaScript functions and are responsible to do specific tasks only. AngularJS has about 30 built-in services. One of them is the $location, $http, $provide, $resource, $window, $parse service.
Different ways to create service in AngularJS: Factory
Factory is a simple function which allows you to add some logic before creating the object. It returns the created object.
Output
When to use: It is just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are using it with constructor function.
Service:
Service is a constructor function which creates the object using new keyword. You can add properties and functions to a service object by using this keyword. Unlike factory, it doesn’t return anything.
Output
When to use: It is a singleton object. Use it when you need to share a single object across the application.
Provider:
A provider is used to create a configurable service object. It returns value by using $get () function, $provide service has a number of methods for registering components with the $injector.
Output
When to use:
When you need to provide module-wise configuration for your service object before making it available.
Value:
You can also register a function as a value. Values are typically used as configuration which is injected into factories, services or controllers.
Output:
Constant:
It is like a value. Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function and it cannot be overridden by an Angular decorator.
Output:
Decorator:
A decorator can modify or encapsulate other providers. There is one exception and that a constant cannot be decorated.
Summary:
- Overview Of AngularJS: Part 1
- Start With AngularJS: Part 2
- Start With AngularJS: Part 3
- Start Up With AngularJS Part: 4
- Start With AngularJS: Part 5
What is a Service
Services are JavaScript functions and are responsible to do specific tasks only. AngularJS has about 30 built-in services. One of them is the $location, $http, $provide, $resource, $window, $parse service.
Different ways to create service in AngularJS: Factory
Factory is a simple function which allows you to add some logic before creating the object. It returns the created object.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Factory Demo</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
- </script>
- <script>
- var app = angular.module('app', []);
- app.controller("MemberController", function($scope, myFactory)
- {
- $scope.FirstName = myFactory.FirstName;
- $scope.FullName = myFactory.FullName;
- });
- app.factory('myFactory', function()
- {
- varmyName = "Shiva";
- function getName()
- {
- return myName;
- }
- return
- {
- FullName: getName() + " " + "shukla",
- FirstName: getName()
- };
- });
- </script>
- </head>
- <body ng-app="app">
- <p>AngularJS Factory</p>
- <div ng-controller="MemberController">
- <p>
- FirstName: {{FirstName}}
- </p>
- <p>
- FullName: {{FullName}}
- </p>
- </div>
- </body>
- </html>
When to use: It is just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are using it with constructor function.
Service:
Service is a constructor function which creates the object using new keyword. You can add properties and functions to a service object by using this keyword. Unlike factory, it doesn’t return anything.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Service Demo</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
- </script>
- <script>
- var app = angular.module('app', []);
- app.controller('MemberController', function($scope, myService)
- {
- $scope.FirstName = myService.FirstName();
- $scope.FullName = myService.FullName;
- });
- app.service('myService', function()
- {
- varmyName = "Shiva";
- this.FirstName = function()
- {
- return myName;
- }
- this.FullName = myName + " " + "shukla"
- });
- </script>
- </head>
- <body ng-app="app">
- <p>AngularJS Service</p>
- <div ng-controller="MemberController">
- <p>
- FirstName: {{FirstName}}
- </p>
- <p>
- FullName: {{FullName}}
- </p>
- </div>
- </body>
- </html>
When to use: It is a singleton object. Use it when you need to share a single object across the application.
Provider:
A provider is used to create a configurable service object. It returns value by using $get () function, $provide service has a number of methods for registering components with the $injector.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Provider Demo</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
- </script>
- <script>
- var app = angular.module('app', []);
- app.config(["myProviderServiceProvider", function(myProviderService)
- {
- myProviderService.set("shiva", "shukla");
- }]);
- app.controller("MemberController", function($scope, myProviderService)
- {
- $scope.FirstName = myProviderService.FirstName();
- $scope.LastName = myProviderService.LastName();
- $scope.FullName = myProviderService.FullName;
- });
- app.provider('myProviderService', function()
- {
- var myFName = "Shiva";
- var myLName = "Shukla";
- return {
- set: function(fName, lName)
- {
- myFName = fName;
- myLName = lName;
- },
- $get: function()
- {
- functiongetFName()
- {
- returnmyFName;
- }
- functiongetLName()
- {
- returnmyLName;
- }
- return
- {
- FullName: myFName + " " + myLName,
- FirstName: getFName,
- LastName: getLName
- };
- }
- };
- });
- </script>
- </head>
- <body ng-app="app">
- <p>AngularJS Provider</p>
- <div ng-controller="MemberController">
- <p>
- FirstName: {{FirstName}} and LastName : {{LastName}}
- </p>
- <p>
- FullName: {{FullName}}
- </p>
- </div>
- </body>
- </html>
When to use:
When you need to provide module-wise configuration for your service object before making it available.
Value:
You can also register a function as a value. Values are typically used as configuration which is injected into factories, services or controllers.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Value Demo</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
- </script>
- <script>
- var app = angular.module('app', []);
- app.controller("MemberController", function($scope, numberValue, stringValue, objectValue)
- {
- $scope.numberValue = numberValue;
- $scope.stringValue = stringValue;
- $scope.objectValue = objectValue;
- });
- app.value("numberValue", 1000);
- app.value("stringValue", "Hello Word");
- app.value("objectValue",
- {
- objVal1: true,
- objVal2: "My object Value"
- });
- </script>
- </head>
- <body ng-app="app">
- <p>AngularJS Value</p>
- <div ng-controller="MemberController">
- <p>
- number Value: {{numberValue}}
- <br/> string Value: {{stringValue}}
- <br/> object Value : {{objectValue.objVal1}} and {{objectValue.objVal2}}
- </p>
- </div>
- </body>
- </html>
Constant:
It is like a value. Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function and it cannot be overridden by an Angular decorator.
- <!DOCTYPE html>
- <html>
- <head>
- <title>Constant Demo</title>
- <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
- </script>
- <script>
- var app = angular.module('app', []);
- app.controller('MemberController', function($scope, myConfig)
- {
- $scope.myConfig = myConfig;
- });
- app.constant('myConfig',
- {
- flag: true,
- settings: "default"
- });
- </script>
- </head>
- <body ng-app="app">
- <p>AngularJS Constant</p>
- <div ng-controller="MemberController">
- <p>
- flag: {{myConfig.flag}}
- <br/> settings: {{myConfig.settings}}
- </p>
- </div>
- </body>
- </html>
Decorator:
A decorator can modify or encapsulate other providers. There is one exception and that a constant cannot be decorated.
- var app = angular.module('app', []);
- app.value('movieTitle', 'Airlift');
- app.config(function($provide)
- {
- $provide.decorator('movieTitle', function($delegate)
- {
- return $delegate + ' – The rising';
- });
- });
- app.controller('MyController', function(movieTitle)
- {
- expect(movieTitle).toEqual('Airlift – the rising');
- });
- All the providers are instantiated only once. That means that they are all singletons.
- All the providers except constant can be decorated.
- A constant is a value that can be injected everywhere. The value of a constant can never be changed.
- A value is just a simple injectable value.
- A service is an injectable constructor.
- A factory is an injectable function.
- A decorator can modify or encapsulate other providers except a constant.
- A provider is a configurable factory.
Subscribe to:
Posts (Atom)