patternsqlMinor
Composite field in SQL Server, does it exist?
Viewed 0 times
fieldsqlexistdoescompositeserver
Problem
I'm designing a table to be used by a Web App, and my framework requires that the primary key be a surrogate key. But I also need an extra field which will be a composite of 2 other fields. In other words:
UniqueOrderNumber should be a string generated by merging OrderNumber and OrderDate. This new field will then by used in certain queries that require a unique OrderNumber.
I wanted to avoid handling this logic in the application as I feel this should be a job for the databate. Is there a way to have the database generate this UniqueOrderNumber field automatically by concatenating the values of OrderNumber and OrderDate?
Id -> Primary key
OrderNumber
OrderDate
UniqueOrderNumber -> a composite of OrderNumber and OrderDateUniqueOrderNumber should be a string generated by merging OrderNumber and OrderDate. This new field will then by used in certain queries that require a unique OrderNumber.
I wanted to avoid handling this logic in the application as I feel this should be a job for the databate. Is there a way to have the database generate this UniqueOrderNumber field automatically by concatenating the values of OrderNumber and OrderDate?
Solution
You could leverage computed columns for this. So your create table would look like:
SQL Fiddle Example
CREATE TABLE foo
(ID int not null,
OrderNumber int not null,
OrderDate datetime not null,
UniqueOrderNumber AS
(CONVERT(varchar(20),OrderNumber) + ":" + CONVERT(varchar(20),OrderDate,112))
)SQL Fiddle Example
Code Snippets
CREATE TABLE foo
(ID int not null,
OrderNumber int not null,
OrderDate datetime not null,
UniqueOrderNumber AS
(CONVERT(varchar(20),OrderNumber) + ":" + CONVERT(varchar(20),OrderDate,112))
)Context
StackExchange Database Administrators Q#41024, answer score: 6
Revisions (0)
No revisions yet.