我需要执行一次性操作,并且希望我能用SQL语句(在LINQPad中)执行此操作。我需要从两个表中获取数据,然后将这些val插入另一个表中。具体来说,我需要使用Customers表中的Unit / MemberNo / CustNo的每个唯一组合的数据填充CustomerCategoryLog表,并从MasterUnitsProjSales表中添加相应的NewBiz值。
Pseudo-SQL就是这样的:
// 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)
如果上面的古怪的伪SQL难以理解,那就是我需要的:
如果NewBiz = 1,则在“类别”和“子类别”字段中存储“现有”;否则,在这两个字段中存储“新”。
如果这需要是StoredProc,它需要看起来像什么?
另一个选择是在C#中编写一个实用程序来检索数据,然后遍历结果集,有条件地将“New”或“Existing”记录插入到CustomerCategoryLog表中。
我认为必须有一种更快捷的方法来使用T-SQL来完成它。
答案 0 :(得分:3)
你所追求的是case
陈述......
首先尝试将其作为select
来测试输出:
--// 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