I have a SQL table with many columns, and in particular a set of columns containing codes. For each of the code columns there are also corresponding information columns pertaining to each of the code columns. I need to be able to turn one record into multiple returned records (i.e. one record for each code). This is an old table with legacy data along with software code, and it would be very difficult to normalize the table (even though it really needs to be).
Here is the table:
CO_ComapnyInformation
(
ProjectID
,SubContractor_OrgID
,BudGet
,ContractDays
,ContractCode
,ContractCode1
,ContractCode2
,ContractCode3
,ContractCode4
,ContractCode5
,ContractCodeAmt
,ContractCode1Amt
,ContractCode2Amt
,ContractCode3Amt
,ContractCode4Amt
,ContractCode5Amt
,ContractStartDate
,ContractCodeBudget
,ContractCodeBudget1
,ContractCodeBudget2
,ContractCodeBudget3
,ContractCodeBudget4
,ContractCodeBudget5
,ContractCodeAdjust
,ContractCodeAdjust1
,ContractCodeAdjust2
,ContractCodeAdjust3
,ContractCodeAdjust4
,ContractCodeAdjust5
,ContractCodeUncommit
,ContractCodeUncommit1
,ContractCodeUncommit2
,ContractCodeUncommit3
,ContractCodeUncommit4
,ContractCodeUncommit5
,ContractCodeSaveOR
,ContractCodeSaveOR1
,ContractCodeSaveOR2
,ContractCodeSaveOR3
,ContractCodeSaveOR4
,ContractCodeSaveOR5
)
basically I need the returned recordset to look like this:
Contract Code | Contract Budget | Contract Adjust | Contract Uncommit | Contract SaveOR | Pro_ID | ...
ContractCode 10.00 xxxx
ContractCode1
ContractCode2
etc…
Only if the COntractCode columns have data in them.
How do I do this?
You can use
union allto do it.Maybe you don’t need that first column (
ContractCodeType), it’s just so you can know from which set of values the row came from.Ideally though, if those fields store the same type of information, it’s better to have a simpler table only with one set of fields. You can start with a view on top of it (that’s basically the
unioncode above), and refactor your application in small steps.