【问题标题】:how to insert Date into TempTable inside Cursor?如何将日期插入游标内的 TempTable?
【发布时间】:2020-09-16 06:42:19
【问题描述】:

我有一个光标(仅用于练习和测试光标),我想将我的结果插入到 TempTable 我试过这个但是我得到了这个错误

游标声明中不允许使用 INTO 子句。

我的代码:

DECLARE cursor_brand CURSOR FOR
     SELECT firstname, LastName 
     INTO #tempTable_2 
     FROM Person.Person
     JOIN Sales.SalesOrderDetail ON SalesOrderDetail.SalesOrderDetailID = Person.BusinessEntityID
     JOIN Sales.SalesOrderHeader ON SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID
     WHERE OrderDate LIKE '%2011%' AND LineTotal > 10000
     ORDER BY LastName

OPEN cursor_brand;

FETCH NEXT FROM cursor_brand

WHILE @@FETCH_STATUS = 0
    FETCH NEXT FROM cursor_brand
    CLOSE cursor_brand
    DEALLOCATE cursor_brand;

【问题讨论】:

  • 由于多种原因,您不能使用
  • @SM你能给我举个例子吗?
  • 我可以——但是你错过了应该通过阅读文档、搜索互联网以及学习何时(以及何时不)使用光标来获得的学习体验。提示 - 在循环内部是插入语句所在的位置 - 只是一个简单的 。但是不清楚为什么在一个语句中很容易做到这一点时,为什么要关注游标。

标签: sql sql-server cursor sql-insert temp-tables


【解决方案1】:

我真的不明白你为什么需要一个光标。要插入临时表,使用 select ... into ... 语法就足够了,所以我认为你的整个代码应该简化为:

select p.firstname, p.LastName 
into #tempTable_2
from Person.Person p
join Sales.SalesOrderDetail sod on sod.SalesOrderDetailID = p.BusinessEntityID
join Sales.SalesOrderHeader soh on soh.SalesOrderID = sod.SalesOrderID
where soh.OrderDate like '%2011%' and sod.LineTotal > 10000

请注意,我使用表别名来缩短查询 - 我必须对 select 和 where 子句中的列做出假设。如果这些假设是正确的,那么您只选择person 列,所以我实际上不确定这段代码是否完全符合您的要求:如果一个人有多个满足salesOrder 和salesOrderDetail 条件的行,那么它将在临时表中多次插入。您可以通过使用exists 而不是joins 来避免这种情况:

select p.firstname, p.LastName 
into #tempTable_2
from Person.Person p
where exists (
    select 1 
    from Sales.SalesOrderDetail sod
    join Sales.SalesOrderHeader soh on soh.SalesOrderID = sod.SalesOrderID
    where 
        soh.OrderDate like '%2011%' 
        and sod.LineTotal > 10000
        and sod.SalesOrderDetailID = p.BusinessEntityID
)

最后,如果soh.OrderDate 是类似date 的数据类型(应该如此),那么您应该使用日期函数而不是字符串函数来过滤它。也就是说,替换这个:

soh.OrderDate like '%2011%' 

与:

soh.OrderDate >= '2011-01-01' and soh.OrderDate < '2012-01-01'  

【讨论】:

    猜你喜欢
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    相关资源
    最近更新 更多