我有一个游标(仅用于练习和测试游标),我想将我的结果插入到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;
我真的不明白为什么您这里需要光标。要插入到临时表中,使用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
而不是join
s来避免这种情况:
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'