我有一个需要执行的一次性操作,我希望我可以用 SQL 语句(在 LINQPad 中)来完成它。我需要从两个表中获取数据,然后将这些值插入到另一个表中。具体来说,我需要使用 Customers 表中 Unit/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)
如果上面古怪的伪 SQL 难以理解,这就是我需要的:
如果 NewBiz = 1,则在 Category 和 Subcategory 字段中存储“Existing”;否则,在这两个字段中都存储“New”。
如果这需要是一个 StoredProc,它需要看起来像什么?
另一种选择是用 C# 编写一个实用程序来检索数据,然后遍历结果集,有条件地将"new"或“现有”记录插入 CustomerCategoryLog 表。
不过,我认为必须有一种使用 T-SQL 来完成它的更快的方法。
最佳答案
你要的是一个case
语句...
首先尝试将其作为选择
来测试输出:
--// 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
关于sql-server - 如何填充临时表、过滤它们,然后循环遍历 (SQL Server)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42706099/