|
Using Derived Columns
|
|
SQL Server supports the creation of derived columns. Derived columns are those that get their values from other columns in a table. For example, assume that you have a table called "Orders". Let's assume that the order identification number that is to be used for all external communications must be prefixed with an "ORD" and a 4 digit number, which is the "Orders" table primary key. This is quite a common requirement and most applications in the past used to "manage" this column independently and write application code that will generate this column. With SQL Server 2000 derived columns, this is very simple to implement. Here is how we can achieve this:
In the above CREATE TABLE snippet, we can see that the "ExternalOrderID" is a derived column, based on the rules as we said above. Now when you insert data into the table, the columns is auto generated. For example, if we issue the following INSERT statement:
We can see that the "ExternalOrderID" has the value ORD0001. That's a pretty good functionality, right!! :-) As another example, consider that you have a date column and you want to store the date and time seperately. Here is how you can do it in SQL Server.
The two derived columns in the end of the above snippet split the date field into the date and time components using the CONVERT function. Now, you can insert data into the table as follows:
Check out the output and it has the information that we want...One immediate question that comes to our mind is "can I index derived columns??". Yes, you can, but subject to the following conditions.
|
| Home |