如何填充临时表、过滤它们,然后循环遍历 (SQL 服务器)?

How can I populate temporary tables, filter them, and then loop through (SQL Server)?

我有一个一次性的操作需要执行,我希望我可以用 SQL 语句(在 LINQPad 中)来完成它。我需要从两个 table 中获取数据,然后将这些 val 插入另一个。具体来说,我需要使用来自客户 table 的 Unit/MemberNo/CustNo 的每个唯一组合的数据填充 CustomerCategoryLog table,添加来自 MasterUnitsProjSales table 的相应 NewBiz 值。

伪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,则在类别和子类别字段中存储 'Existing';否则,将 'New' 存储在这两个字段中。

如果这需要是 StoredProc,它需要看起来像什么?

另一个选择是用 C# 编写一个实用程序来检索数据,然后遍历结果集,有条件地将 'New' 或 'Existing' 记录插入 CustomerCategoryLog table .

不过,我想一定有一种更快的方法可以使用 T-SQL 来完成它。

您要的是 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