Tuesday, November 24, 2009

Cascading Referential Integrity Constraints

By using cascading referential integrity constraints, you can define the actions that the SQL Server takes when a user tries to delete or update a key to which existing foreign keys point.

The REFERENCES clauses of the CREATE TABLE and ALTER TABLE statements support the ON DELETE and ON UPDATE clauses. Cascading actions can also be defined by using the Foreign Key Relationships dialog box:

* [ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]
* [ ON UPDATE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ]

NO ACTION is the default if ON DELETE or ON UPDATE is not specified.

ON DELETE NO ACTION

Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, an error is raised and the DELETE statement is rolled back.

ON UPDATE NO ACTION

Specifies that if an attempt is made to update a key value in a row whose key is referenced by foreign keys in existing rows in other tables, an error is raised and the UPDATE statement is rolled back.

CASCADE, SET NULL and SET DEFAULT allow for deletions or updates of key values to affect the tables defined to have foreign key relationships that can be traced back to the table on which the modification is performed. If cascading referential actions have also been defined on the target tables, the specified cascading actions also apply for those rows deleted or updated. CASCADE cannot be specified for any foreign keys or primary keys that have a timestamp column.

ON DELETE CASCADE

Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, all rows that contain those foreign keys are also deleted.

ON UPDATE CASCADE

Specifies that if an attempt is made to update a key value in a row, where the key value is referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key are also updated to the new value specified for the key.
ms186973.note(en-us,SQL.100).gifNote:
CASCADE cannot be specified if a timestamp column is part of either the foreign key or the referenced key.

ON DELETE SET NULL

Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to NULL. All foreign key columns of the target table must be nullable for this constraint to execute.

ON UPDATE SET NULL

Specifies that if an attempt is made to update a row with a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to NULL. All foreign key columns of the target table must be nullable for this constraint to execute.

ON DELETE SET DEFAULT

Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to their default value. All foreign key columns of the target table must have a default definition for this constraint to execute. If a column is nullable, and there is no explicit default value set, NULL becomes the implicit default value of the column. Any nonnull values that are set because of ON DELETE SET DEFAULT must have corresponding values in the primary table to maintain the validity of the foreign key constraint.

ON UPDATE SET DEFAULT

Specifies that if an attempt is made to update a row with a key referenced by foreign keys in existing rows in other tables, all the values that make up the foreign key in the rows that are referenced are set to their default value. All foreign key columns of the target table must have a default definition for this constraint to execute. If a column is nullable, and there is no explicit default value set, NULL becomes the implicit default value of the column. Any non-null values that are set because of ON UPDATE SET DEFAULT must have corresponding values in the primary table to maintain the validity of the foreign key constraint.

Consider the FK_ProductVendor_Vendor_VendorID constraint on the Purchasing.ProductVendor table in AdventureWorks. This constraint establishes a foreign key relationship from the VendorID column in the ProductVendor table to the VendorID primary key column in the Purchasing.Vendor table. If ON DELETE CASCADE is specified for the constraint, deleting the row in Vendor where VendorID equals 100 also deletes the three rows in ProductVendor where VendorID equals 100. If ON UPDATE CASCADE is specified for the constraint, updating the VendorID value in the Vendor table from 100 to 155 also updates the VendorID values in the three rows in ProductVendor whose VendorID values currently equal 100.

ON DELETE CASCADE cannot be specified for a table that has an INSTEAD OF DELETE trigger. For tables that have INSTEAD OF UPDATE triggers, the following cannot be specified: ON DELETE SET NULL, ON DELETE SET DEFAULT, ON UPDATE CASCADE, ON UPDATE SET NULL, and ON UDATE SET DEFAULT.
Multiple Cascading Actions

Individual DELETE or UPDATE statements can start a series of cascading referential actions. For example, a database contains three tables: TableA, TableB, and TableC. A foreign key in TableB is defined with ON DELETE CASCADE against the primary key in TableA. A foreign key in TableC is defined with ON DELETE CASCADE against the primary key in TableB. If a DELETE statement deletes rows in TableA, the operation also deletes any rows in TableB that have foreign keys matching the deleted primary keys in TableA, and then deletes any rows in TableC that have foreign keys that match the deleted primary keys in TableB.

The series of cascading referential actions triggered by a single DELETE or UPDATE must form a tree that contains no circular references. No table can appear more than one time in the list of all cascading referential actions that result from the DELETE or UPDATE. Also, the tree of cascading referential actions must not have more than one path to any specified table. Any branch of the tree is ended when it encounters a table for which NO ACTION has been specified or is the default.
Triggers and Cascading Referential Actions

Cascading referential actions fire the AFTER UPDATE or AFTER DELETE triggers in the following manner:

All the cascading referential actions directly caused by the original DELETE or UPDATE are performed first.

If there are any AFTER triggers defined on the affected tables, these triggers fire after all cascading actions are performed. These triggers fire in opposite order of the cascading action. If there are multiple triggers on a single table, they fire in random order, unless there is a dedicated first or last trigger for the table. This order is as specified by using sp_settriggerorder.

If multiple cascading chains originate from the table that was the direct target of an UPDATE or DELETE action, the order in which these chains fire their respective triggers is unspecified. However, one chain always fires all its triggers before another chain starts firing.

An AFTER trigger on the table that is the direct target of an UPDATE or DELETE action fires regardless of whether any rows are affected. There are no other tables affected by cascading in this case.

If any one of the previous triggers perform UPDATE or DELETE operations on other tables, these actions can start secondary cascading chains. These secondary chains are processed for each UPDATE or DELETE operation at a time after all triggers on all primary chains fire. This process may be recursively repeated for subsequent UPDATE or DELETE operations.

Performing CREATE, ALTER, DELETE, or other data definition language (DDL) operations inside the triggers may cause DDL triggers to fire. This may subsequently perform DELETE or UPDATE operations that start additional cascading chains and triggers.

If an error is generated inside any particular cascading referential action chain, an error is raised, no AFTER triggers are fired in that chain, and the DELETE or UPDATE operation that created the chain is rolled back.

A table that has an INSTEAD OF trigger cannot also have a REFERENCES clause that specifies a cascading action. However, an AFTER trigger on a table targeted by a cascading action can execute an INSERT, UPDATE, or DELETE statement on another table or view that fires an INSTEAD OF trigger defined on that object.
Cascading Referential Constraints Catalog Information

Querying the sys.foreign_keys catalog view returns the following values that indicate the cascading referential constraint specified for a foreign key.
Value Description

0 NO ACTION
1 CASCADE
2 SET NULL
3SET DEFAULT

The UPDATE_RULE and DELETE_RULE columns returned by sp_fkeys and sp_foreignkeys return 0 when CASCADE, SET NULL, or SET DEFAULT is specified; and return 1 when NO ACTION is specified or is the default.

When a foreign key is specified as the object of sp_help, the output result set contains the following columns.

Column name Data type Description
delete_action nvarchar(9) Indicates whether the delete action is CASCADE,
SET NULL, SET DEFAULT, NO ACTION, or N/A
(not applicable).
update_action nvarchar(9) Indicates whether the update action is CASCADE,
SET NULL, SET DEFAULT, NO ACTION, or N/A
(not applicable).

Referential integrity constraints in SQL Server

Cascading referential integrity constraints are foreign key constraints that tell SQL Server to perform certain actions when a primary key field in a primary key-foreign key relationship is updated or deleted. By using cascading referential integrity constraints, you can define the actions that SQL Server 2005 takes when a user tries to delete or update a key to which existing foreign keys point.

SQL Server allows you to define cascading referential integrity constraints. These actions have a trickle-down or cascading effect, sometimes affecting several tables that were related to the primary key table. Let’s look at how these constraints are defined, and some situations where you can use them.

The following script sets up the tables that I will use to look at cascading referential constraints:

IF OBJECT_ID('SalesHistory') > 0
DROP TABLE SalesHistory
GO
CREATE TABLE SalesHistory
(
SaleID int IDENTITY(1,1) NOT NULL,
ProductID TINYINT,
CustomerID INT,
SaleDate datetime NULL,
SalePrice money NULL,
CONSTRAINT pk_SaleID PRIMARY KEY (SaleID)
)
GO
IF OBJECT_ID('Customers') > 0
DROP TABLE Customers
GO
CREATE TABLE Customers
(
CustomerID INT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
CONSTRAINT pk_CustomerID PRIMARY KEY (CustomerID)
)
GO
IF OBJECT_ID('Products') > 0
DROP TABLE Products
GO
CREATE TABLE Products
(
ProductID TINYINT,
ProductDescription VARCHAR(100),
CONSTRAINT pk_ProductID PRIMARY KEY (ProductID)
)
GO

Relationships between tables are required for cascading updates or delete statements; these relationships are defined through FOREIGN KEY constraints. (Here’s more information on defining SQL Server constraints.) The code below defines a relationship between the SalesHistory and the Customers tables and a relationship between the SalesHistory and the Products tables.

ALTER TABLE SalesHistory
ADD CONSTRAINT fk_SalesHistoryCustomerID FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ON DELETE SET NULL ON UPDATE SET NULL
ALTER TABLE SalesHistory
ADD CONSTRAINT fk_SalesHistoryProductID FOREIGN KEY (ProductID) REFERENCES Products(ProductID) ON DELETE CASCADE ON UPDATE CASCASE
GO

The previous script introduces the cascading referential integrity options. In the first statement, I use the ON UPDATE SET NULL option; in the second statement, I use the ON DELETE CASCADE ON UPDATE CASCADE option. Here’s an overview of what these constraints mean.

SET NULL
If a delete statement affects rows in a foreign key table, those values will be set to NULL when the primary key record is deleted. If an update statement affects rows in the foreign key table, those rows will be updated with the value NULL after the primary key record has been updated. The foreign key columns affected must allow NULL values.

CASCADE
If a delete statement affects one or more rows in a foreign key table, those rows will be deleted when the primary key record is deleted. If an update statement affects rows in the foreign key table, those rows will be updated with the value from the primary key record after it has been updated.

SET DEFAULT
All the values that make up the foreign key in the rows that are referenced are set to their default value. All foreign key columns in the related table must have default constraints defined on them.

NO ACTION
This is the default action. This specifies that if an update or delete statement affects rows in foreign key tables, the action will be denied and rolled back. An error message will be raised.

To see how these constraints work, I’ll add some data to my tables.

INSERT INTO Products
(
ProductID, ProductDescription
)
SELECT 1, 'BigScreen'
UNION ALL
SELECT 2, 'Computer'
UNION ALL
SELECT 3, 'PoolTable'
GOINSERT INTO Customers(CustomerID , FirstName , LastName )
SELECT 1, 'Jason', 'Tomes'
UNION ALL
SELECT 2, 'Chris', 'Robards'
UNION ALL
SELECT 3, 'Megan', 'Hill'
UNION ALL
SELECT 4, 'Wanda', 'Guthrie'
UNION ALL
SELECT 5, 'Lilly', 'Cunningham'
UNION ALL
SELECT 6, 'Amanda', 'Travis'
UNION ALL
SELECT 7, 'Willy', 'Grant'
UNION ALL
SELECT 8, 'Zach', 'Tacoma'
UNION ALL
SELECT 9, 'Marty', 'Smith'
UNION ALL
SELECT 10, 'Wendi', 'Jones'
UNION ALL
SELECT 11, 'Angie' , 'Corolla'
UNION ALL
SELECT 12, 'Shelly', 'Hartson'
GO

I can load sample data into the SalesHistory table. Because I am using a numeric value to represent the customers, I can generate the CustomerID number with relative ease with the use of the modulus operator.

DECLARE @i SMALLINT
SET @i = 1
WHILE (@i <=100)
BEGIN
INSERT INTO SalesHistory(ProductID, SaleDate, SalePrice, CustomerID)
VALUES(1, DATEADD(mm, @i, '3/11/1919'), DATEPART(ms, GETDATE()) + (@i + 57), ((DATEPART(ms, GETDATE()) + (@i + 29)) % 12) + 1)
INSERT INTO SalesHistory(ProductID, SaleDate, SalePrice, CustomerID)
VALUES(2, DATEADD(mm, @i, '3/11/1927'), DATEPART(ms, GETDATE()) + (@i + 13), ((DATEPART(ms, GETDATE()) + (@i + 29)) % 12) + 1)
INSERT INTO SalesHistory(ProductID, SaleDate, SalePrice, CustomerID)
VALUES(3, DATEADD(mm, @i, '3/11/1908'), DATEPART(ms, GETDATE()) + (@i + 29), ((DATEPART(ms, GETDATE()) + (@i + 29)) % 12) + 1)
SET @i = @i + 1
END

Now let’s see if the constraints I set up work. The script below deletes a customer record from my Customers table. Because the cascading constraint indicates ON DELETE SET NULL, the associated records in the SalesHistory table will have the value NULL for the CustomerID column where that column had the value of 6 before the update.

DELETE FROM Customers
WHERE CustomerID = 6

This script invokes the ON DELETE CASCADE constraint defined on the SalesHistory table. This means that when a record is deleted from the Products table, and it is related to a record in the SalesHistory table, those SalesHistory records will be deleted from the table.

DELETE FROM Products
WHERE ProductID = 1
Cascade with care

You can use cascading constraints in SQL Server to set related values to NULL, to set affected values to original default values, or to delete columns. While it’s great to have these capabilities in a testing or quality assurance environment (where data is not production data and consistently reused), I don’t recommend allowing these types of constraints in a production environment. The reason for this is that these constraints may lead to results that you or other programmers on your team are not aware of, and so their code may not be able to handle the actions from the cascading constraint.

If you are in a situation where you need to delete related data from different tables, it has been my experience to have defined procedures in place to do so, rather than to rely on the database to do this for you.

Thursday, November 19, 2009

Whidbey ASP.NET V2.0 New Features

In this article, we are going to see the new features of Whidbey ASP.NET V2.0. This is just the tip of the ice berg. Whidbey ASP.NET V2.0 comes with whole lot of new features. I will keep updating this article, as and when I find any new features in ASP.NET V2.0. Here is the some of the new features which i found interesting.

Cross-page posting

In Whidbey, you will be able to post Web Forms to pages other than the page on which the input is entered. Postback target is chosen based on the PostTargetUrl attribute of a control that causes a postback. On the target page, you will be able to access all of the controls, viewstate, etc. of the page that caused the web form post. Whidbey passes a page object called PreviousPage to the current page for accessing controls,viewstate and all others contents of previous page. For example consider you are filling your personal details in one page and then you need to post this details to next page for processing. In ASP.NET v1.0 you need to post this values to that same page and then you need to redirect to the next page. But in Whidbey you can directly post this values to the next page.

Page1.aspx


Name




Page2.aspx.vb
Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label1.Text = DirectCast(PreviousPage.FindControl("TextBox1"), System.Web.UI.WebControls.TextBox).Text
End Sub
ValidationGroups

You can now have validator controls optionally validate depending on which button on the page is pushed. You can group validation rules into “groups“ so that all controls within that group fire or don't fire.The new feature validation groups allows you to logically group a set of validation controls, and only validate the fields that are in the group to which belongs the postback control that the user clicks. Uses the ValidationGroup attribute to implement in declarative tags. The key here is that you can have two sets of form fields that aren't typically used together, and implement validation on both sets of fields, without the non-used fields causing the page to fail validation. This feature is very useful in the page where you are having two sets of forms for example you might have a page which has search pane in the top and the registration details at the bottom. when find button is clicked you need to validate only the search page controls and similarly when you press create login, you need to validate the controls in registration form. For this type of requirement, this validation groups is very useful. In our example, we have two textbox and two buttons. When one button is pressed we need to validate only one textbox and similarly for other button. Each button has validationgroup attribute set to particular groups which will validate only one textbox.


Name
Address




*
*

Wizard UI

New control that enables step-by-step wizard UI, for example for gathering multiple pages of input for a single purpose before saving or processing the input. The Wizard control defaults to a Next/Previous UI, but is also templated, so you can customize the UI to your needs. In ASP.NET v1.1, if you want to fill lots of details either you need to place all the controls in one page or create multiple pages for groups of controls for providing wizard kind of approach. But in whidbey you have a new control called Wizard control which will do this type of work with one page but providing wizard kind of approach. Check out the following code and find out how easy to create wizard in ASP.NET V2.o








Step 1 : Fill your Name


Step 2 : Fill your Address




You can find new tags like ,,,. Using stepnavigationtemplate you can define the controls that needs to be placed in the navigation template. For example you need to place two button controls and then set id for the controls as stepnextbutton and steppreviousbutton. Then automatically navigation feature will be there for you wizards. For putting controls in each step you can use wizardsteps tag.
ASP.NET Themes

A theme is a collection of property settings that allow you to define the look of pages and controls and then apply the look consistently across pages. You can apply theme settings to an entire application (Web site), to a page and its controls, or to an individual control. If you take popular websites like yahoo they have implemented theme in their site, for example you need to have theme of yellow color. Then you will view that website in yellow color if you want to change to red, then all the controls will change to red. ASP.NET makes available some predefined themes (global themes) that can be applied to any ASP.NET Web application. For example, ASP.NET includes a theme called BasicBlue that defines a common style for most ASP.NET Web server controls.You can create your own themes, called page themes, to apply to your site or to individual pages.
ASP.NET Site Navigation

When you create Web applications that consist of anything more than a few pages, you will find it useful to provide a consistent way for users to navigate around the site. One solution is to include hyperlinks within pages that allow users to jump to other pages. However, if your site becomes large and as you move pages in the site, it quickly becomes difficult to manage all the links. To create consistent, easily managed navigation for your site, you can use ASP.NET site navigation. If you take this website you can see site navigation bar at the left side. This site navigation can be created with very minimal code using following two new controls ,

SiteMapPath control: This control displays a navigation path (also known as a breadcrumb or eyebrow) that shows the user the current page location and displays links as a path back to the home page. The control provides many options for customizing the appearance of the links.

TreeView controls: This control displays a tree structure, or menu, that users can traverse to get to different pages in your site.

URL Rewriting/Mapping

New built-in module for rewriting paths. With this new feature you can map url's to aspx pages in web.config file. This feature can be used to hide the url from the user. If you need to change the location of your aspx page, then you no need to worry. Just change your url mappings in web.config. Since user is exposed to a url which doesnt change you wont get 404 error. Web.config setting for urlmapping is as follows.




If you are requesting for UrlMappings.aspx, then actually you will get the response of Crosspage.aspx. But the user will think that he is getting UrlMappings.aspx only. If you change the Crosspage.aspx location also, you only need to change this setting in web.config.

Site Counters

This feature can be used to montior a web site. For example if you want to know during certain time if you want to know how many hits is made to a particular virutal folder or file. Then you can use this feature. This services exposes many API's like GetTotalCount,GetRows,GetTotalNavigateUrlCount,etc for monitoring a website. Can also be accessed through attributes (CountClicks, CounterGroup, etc.) on declarative tags, as well as through web.config. Using this feature you can efficiently log or report page hits,button click in a page or any other events. For enabling Site counters, you need to place following code in web.config







Client Script Goodies

Server buttons now have an OnClientClick attribute for client-side handling. Focus mechanisms are now built into the page and controls. A page can also have a default button and a default focused control. All these features emit the appropriate client-side script. There will also be automatic scroll position maintenance in the beta release of Whidbey. Here are few examples


No-compile Pages

In web.config, you can configure at the page and folder level whether pages can be compiled after they've been deployed. You can set the compilation option even at page directive. If compilation is disabled, any change to the page after the page or directory has been locked down will throw an exception.





Various options for Compilation mode are Never,Auto and Always.
Image Generation

New feature for generating images in Whidbey. Includes an HttpHandler (.asix) providing a custom handler and base class for image generation, including support for downlevel rendering. Also includes a new DynamicImage control that uses callbacks with the image generation handler to pull down dynamically generated files. .asix files use the @ Image directive and inherit from System.Web.UI.Image.ImageGenerator. Does not require registering your own custom HttpHandler for image generation. Just write the code.

The control supports databinding. You can bind its imagebytes property to a data column that contains binary image data. Using the new Image Generation Service and asp:DynamicImage server control. Show databinding a photo-album where all images are stored in the database, and bound to the asp:DynamicImage control within a asp:DataList template.

File System Provider

It allows Web content (both compiled and non-compiled) to be stored in non-filesystem locations such as databases or CMS, and even use Sql Cache invalidation to output cache stored content, while always getting the updated content if it changes. Pretends to be the filesystem and provides an interface into whatever storage location the content is actually stored in. Cannot store assemblies, but can store just about any other content.


Note :- More information about it from the given link
http://weblogs.asp.net/scottgu/archive/2003/10/22/32965.aspx