问题
I have a one-time operation I need to perform, and am hoping I can do it with a SQL statement (in LINQPad). I need to grab data from two tables, then insert those vals into another one. Specifically, I need to populate the CustomerCategoryLog table with data for each unique combination of Unit/MemberNo/CustNo from the Customers table, adding the corresponding NewBiz value from the MasterUnitsProjSales table.
Pseudo-SQL is something like this:
// First, need each unique combination of Unit, MemberNo, and CustNo from the Customers table and NewBiz from the MasterUnitsProjSales table
select distinct C.Unit, C.MemberNo, C.CustNo, M.NewBiz
into #holdingTank
from Customers C
join MasterUnitsProjSales M on M.Unit = C.Unit
// Now, I need to insert records into the CustomerCategoryLog table - New or Existing Category/Subcategory
insert into CustomerCategoryLog (Unit, MemberNo, CustNo , Category, Subcategory, BeginDate, ChangedBy, ChangedOn)
VALUES (select Unit, MemberNo, CustNo, if NewBiz = 1: 'Existing'? 'New', if NewBiz = 1: 'Existing'? 'New', Date.Now(), 'Clay Shannon', Date.Now() from #holdingTank)
If the wacky pseudoSQL directly above is incomprehensible, this is what I need:
if NewBiz = 1, store 'Existing' in both the Category and Subcategory fields; otherwise, store 'New' in both of those fields.
If this needs to be a StoredProc, what does it need to look like?
Another option would be to write a utility in C# to retrieve the data, then loop through the result set, conditionally inserting either 'New' or 'Existing' records into the CustomerCategoryLog table.
I'm thinking there must be a quicker way to accomplish it using T-SQL, though.
回答1:
What you are after is a case
statement...
Try this as a select
first to test output:
--// First, need each unique combination of Unit, MemberNo, and CustNo from the Customers table and NewBiz from the MasterUnitsProjSales table
select distinct C.Unit, C.MemberNo, C.CustNo, M.NewBiz
into #holdingTank
from Customers C
join MasterUnitsProjSales M on M.Unit = C.Unit
--// Now, I need to insert records into the CustomerCategoryLog table - New or Existing Category/Subcategory
--insert into CustomerCategoryLog (Unit, MemberNo, CustNo , Category, Subcategory, BeginDate, ChangedBy, ChangedOn)
select Unit,
MemberNo,
CustNo,
case when NewBiz = 1 then 'Existing' else 'New' end,
case when NewBiz = 1 then 'Existing' else 'New' end,
getdate(),
'Clay Shannon',
getdate()
from #holdingTank
来源:https://stackoverflow.com/questions/42706099/how-can-i-populate-temporary-tables-filter-them-and-then-loop-through-sql-ser