我如何填充临时表,过滤它们,然后循环(SQL Server)



我有一个我需要执行的一次操作,希望我可以使用SQL语句(在LINQPAD中)进行操作。我需要从两个表中获取数据,然后将这些阀插入另一个阀。具体来说,我需要从客户表中使用单位/MemberNo/Custno的每个唯一组合的数据填充CustomerCategoryLog表,并从Masterunitsprojsales表中添加了相应的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)

如果直接上方的古怪伪Ql是无法理解的,这就是我需要的:

如果newbiz = 1,则将"现有"存储在类别和子类别字段中;否则,将"新"存储在这两个字段中。

如果这需要是一个存储,它需要看起来像什么?

另一个选项是在C#中编写一个实用程序以检索数据,然后循环浏览结果集,将"新"或"现有"记录插入到customerCategorylog表中。

我认为必须使用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

相关内容

最新更新