【问题标题】:How can I populate temporary tables, filter them, and then loop through (SQL Server)?如何填充临时表、过滤它们,然后循环遍历(SQL Server)?
【发布时间】:2017-07-31 01:45:13
【问题描述】:

我有一个一次性操作需要执行,我希望我可以使用 SQL 语句(在 LINQPad 中)来完成。我需要从两个表中获取数据,然后将这些 val 插入另一个表中。具体来说,我需要使用 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)

如果上面直接的古怪pseudoSQL难以理解,这就是我需要的:

如果 NewBiz = 1,则在 Category 和 Subcategory 字段中存储“现有”;否则,在这两个字段中都存储“新”。

如果这需要是一个 StoredProc,它需要是什么样的?

另一种选择是在 C# 中编写一个实用程序来检索数据,然后循环遍历结果集,有条件地将“新”或“现有”记录插入到 CustomerCategoryLog 表中。

不过,我认为必须有一种更快的方法来使用 T-SQL 来完成它。

【问题讨论】:

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


    【解决方案1】:

    您所追求的是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
    

    【讨论】:

    • NB 您可以使用SYSTEM_USER 代替硬编码您的姓名来返回 SQL 登录名。
    • 我先运行了第一个选择块,然后同时尝试了两个,得到“错误 2714:数据库中已经有一个名为 '#holdingTank' 的对象。”然后,当我在第一行添加“drop #holdingTank”时,我得到了“错误 343:CREATE、DROP 或 ALTER 语句中使用的未知对象类型 '#holdingTank'”。不过,它在我的表格列表中不可见...
    • 好的,我忘了在“drop”和临时表的名称之间插入“table”。
    • 你可以在顶部添加if object_id('tempdb..#holdingTank') is not null drop table #holdingTank来处理drop,它会根据需要触发。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多