sql-server - 如何填充临时表、过滤它们,然后循环遍历 (SQL Server)?

标签 sql-server tsql stored-procedures temp-tables select-into

我有一个需要执行的一次性操作,我希望我可以用 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/

相关文章:

sql-server - 需要处理多种场景的存储过程

sql-server - 这是 LEAD() IGNORE NULLS 的错误吗?

sql-server - SQL Server 动态枢轴列名称

c# - con.Open() 失败异常 具有 IsolationLevel 快照的事务无法提升

sql - 如何在SSRS中使用表达式仅显示日期部分?

mysql - T-SQL,比较记录属性,然后进行后续日期比较

mysql - 如何使用mysql中的存储过程获取父子层次结构

php - 从存储过程 MySQL 返回变量

mysql - 在没有 ANY() 的情况下,哪个是最便宜的聚合函数

sql-server - 分组序列的递归 INSERT 查询