IT tutorials
 
Database
 

SQL Server 2008 R2 : Implementing Data Integrity (part 2) - Defaults

12/1/2012 4:48:02 PM
- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
A default provides a value for a column when a value is not supplied. Defaults can be anything that evaluates to a constant, such as a constant, built-in function, or mathematical expression. Defaults are of two types: declarative and bound. The two types are functionally the same; the difference is in how they are implemented.

Declarative Defaults

A declarative default is a constraint defined as part of the table definition. Using declarative defaults is the preferred method for assigning default values to columns. You can use the CREATE TABLE or ALTER TABLE statement to create a default and assign it to a column. Declarative defaults are assigned to a single column and cannot be reused for other columns in the database. The following example shows the creation of a new column named CustomerType in the Sales Customer table followed by the creation of a new default on that column:

ALTER TABLE Sales.Customer
 ADD CustomerType CHAR(1)
ALTER TABLE Sales.Customer ADD CONSTRAINT
    DF_Customer_CustomerType DEFAULT 'I' FOR CustomerType

It is important to remember that a default constraint stores the default value only when a value is not provided during the insertion of a row into the table. The creation of a default constraint does not affect the existing data in the table. UPDATE statements do not utilize the values specified in the default constraint, either, unless the DEFAULT keyword is explicitly referenced; The following example shows an INSERT statement that causes the default value defined in the DF_Customer_CustomerType constraint to be used:

INSERT Sales.Customer
 (TerritoryID)
 SELECT TOP 1 TerritoryID from Sales.SalesTerritory

select CustomerID, CustomerType from Sales.Customer
 where CustomerID = @@identity

/*Results from previous select statement
CustomerID  CustomerType
------------------------
30119       I
*/

The Sales.Customer table in the Adventureworks2008 database is an interesting table because most of the columns have defaults defined, are identity columns, or are nullable. This table has eight columns, but only one value is supplied in the previous example. The rest of the columns, including the CustomerType column, have default definitions that automatically populate the values upon insertion or default to null.

One common misconception with defaults is that a default value is stored when a NULL value is supplied for a column on insertion. However, NULL is considered a value, so the default value is not used in this situation. This is demonstrated in the following example, where the CustomerType column is altered to accept NULL values and then a NULL value is specified for the CustomerType column in the INSERT statement:

ALTER TABLE Sales.Customer
 ALTER COLUMN CustomerType nchar(1) null

INSERT Sales.Customer
 (TerritoryID, CustomerType)
 SELECT TOP 1 TerritoryID, null
  from Sales.SalesTerritory

The insertion in this example succeeds, and the Null value is stored in the CustomerType column that has a default defined on it.

To remove a declarative default constraint, you use ALTER TABLE with the DROP CONSTRAINT clause. The following example removes the DF_Customer_CustomerType constraint from the Sales.Customer table:

ALTER TABLE Sales.Customer DROP CONSTRAINT DF_Customer_CustomerType

Bound Defaults

Bound defaults are similar to rules in that you first create a bound default and then bind it to a column or set of columns. Bound defaults are also similar to rules in that they are slated for removal in a future version of SQL Server. This section covers the basics of bound defaults, but you should keep in mind that Microsoft recommends you avoid using them for new development work.

You use the CREATE DEFAULT command to establish a default that can be bound to a column at a later time. The CREATE DEFAULT syntax is as follows:

CREATE DEFAULT [ schema_name . ] default_name
AS constant_expression [ ; ]

constant_expression can include any constant, built-in function, or mathematical expression. It cannot include user-defined functions. Character and data values that are part of the expression should be enclosed in single quotation marks. Monetary, integer, and floating-point constants do not require the single quotation marks.

The following example creates a default named password_df that can be used to supply a default password for any password-oriented columns:

CREATE DEFAULT password_df AS 'defaultpw'

After you create a default, you can bind it to a column. The following example binds the password_df default to the passwordSalt column on the person.password table:

sp_bindefault password_df, 'person.password.PasswordSalt'

As you can see, a bound default appears to require an extra step, but after it is created, it offers an advantage: you can bind it to other columns. This capability provides some consistency across all the columns that the default is bound to and reduces the overall number of database objects.

When a Default Is Applied

Defaults are applied only when no value is specified for a column during an insertion. They can also be applied during insertions and updates when the DEFAULT keyword is used. To demonstrate the application of defaults, consider the following examples:

CREATE TABLE test_default
(id int IDENTITY NOT NULL,
 tmstmp timestamp NOT NULL,
 password char(13) NOT NULL DEFAULT 'defaultpw',
 Shortdesc VARCHAR(50) NULL)

The table in this example has a unique characteristic: each column has some sort of default value associated with it. One column has a default of NULL because it is nullable. The IDENTITY and TIMESTAMP columns automatically generate values because of their data type, and the password column has an explicit default definition. In this scenario, you can supply the keywords DEFAULT VALUES in the INSERT statement to insert a row of data, as shown in the following example:

INSERT test_default DEFAULT VALUES
select * from test_default
/* results from previous select statement
id          tmstmp             password      Shortdesc
------------------------------------------------------------------
1           0x00000000000007D1 defaultpw     NULL
*/

You can see from the results of the SELECT statement in this example that a row was inserted in the new table, and this row includes default values for all the columns. If you want to supply values for some of the columns and allow the defaults to be used for other columns, you can simply exclude the columns with defaults from the column listing in the INSERT statement. The following example demonstrates how to do this:

INSERT test_default (ShortDesc)
 VALUES('test default insertion')
SELECT * FROM test_default
 where ShortDesc = 'test default insertion'

/* results from previous select statement
id  tmstmp             password   Shortdesc
---------------------------------------------------------
2   0x00000000000007D2 defaultpw  test default insertion
*/

The DEFAULT keyword can also be listed explicitly in the VALUE listing of the INSERT statement, as shown in the following example:

INSERT test_default (tmstmp, password, ShortDesc)
 VALUES(DEFAULT, DEFAULT, DEFAULT)
SELECT * FROM test_default where id = @@identity
/*
(1 row(s) affected)
id  tmstmp             password      Shortdesc
----------------------------------------------
3   0x00000000000007D5 defaultpw     NULL
*/

All the examples so far have dealt with INSERT statements, but there is one scenario in which a default value can be applied with an UPDATE statement. This scenario is similar to the preceding example and requires the use of the DEFAULT keyword. The following example demonstrates the use of the DEFAULT keyword in an UPDATE statement:

UPDATE top (1) test_default
 SET PASSWORD = DEFAULT
GO
SELECT top 1 * from test_default
/*
id          tmstmp             password      Shortdesc
-------------------------------------------------------
1           0x00000000000007DE defaultpw     NULL
*/

Keep in mind that default values are not used for updates unless the DEFAULT keyword is explicitly referenced in the SET clause of the UPDATE statement.

Restrictions on Defaults

When creating defaults, you need to keep in mind the following restrictions:

  • A default cannot be created on columns that have been defined with TIMESTAMP, IDENTITY, or ROWGUIDCOL properties.

  • Only one default can be assigned to a given column. This restriction applies to both declarative and bound defaults.

  • Only one default can exist per column.

  • The default value must be compatible with the data type of the column.

  • A default that is bound cannot be dropped if the default is currently bound to a column. The default must be unbound from the column first.

  • The expression in a default cannot include the names of any columns or other database objects.

There are also some considerations related to the interaction of rules, defaults, and constraints:

  • If a column has both a rule and default, the default is not inserted if it violates the rules.

  • If a default value violates a CHECK constraint, the default is not inserted. Ultimately, all the rules, defaults, and constraints that are active are validated. If the change to the data violates any of them, it is rejected.
 
Others
 
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
Technology FAQ
- Is possible to just to use a wireless router to extend wireless access to wireless access points?
- Ruby - Insert Struct to MySql
- how to find my Symantec pcAnywhere serial number
- About direct X / Open GL issue
- How to determine eclipse version?
- What SAN cert Exchange 2010 for UM, OA?
- How do I populate a SQL Express table from Excel file?
- code for express check out with Paypal.
- Problem with Templated User Control
- ShellExecute SW_HIDE
programming4us programming4us