在sql中一起使用“临时表”和“while循环”

时间:2013-09-14 12:58:42

标签: sql sql-server sql-server-2008

我想创建一个表,然后在while循环中使用表信息。我曾经用'with'来创建表,但我的代码有错误。代码如下:

declare @i integer
set @i=0;

with cte as
(SELECT ROW_NUMBER()OVER(ORDER BY ItemID) as RowNumber,*,DATEDIFF(day,GETDATE(),AdDateTo)as DaysToExpire
FROM KenticoCMS1.dbo.AD_Advertise inner join KenticoCMS1.dbo.CMS_User 
    ON KenticoCMS1.dbo.AD_Advertise.ItemCreatedBy = KenticoCMS1.dbo.CMS_User.UserID
WHERE DATEDIFF(day,GETDATE(),AdDateTo) in (SELECT RemainDays FROM KenticoCMS1.dbo.AD_SendEmailForExpire)
    AND AdShow=1)
--SELECT * FROM cte 

while (  @i<=(select max(RowNumber) from cte))
BEGIN   
        @i=@i+1;
    EXEC msdb.dbo.sp_send_dbmail @profile_name='ExpireAdvertiseEmail',
    @recipients= select Email FROM cte where RowNumber=@i , --'mj.yazdani1988@gmail.com',
    @subject='Test message',
    @body='This is the body of the test message.Congrates Database Mail Received By you Successfully.'      
END
GO

和我的错误:

Msg 156, Level 15, State 1, Line 13
Incorrect syntax near the keyword 'while'.
Msg 156, Level 15, State 1, Line 16
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near ','.

2 个答案:

答案 0 :(得分:1)

您不能将CTE用作临时表。您可以创建表(或声明表变量),将数据放在那里并完成您的工作:

create table #temp (RowNumber int, Email nvarchar(max)

但到目前为止,您的代码可能会像这样更改:

declare @Email nvarchar(max)

declare cur cursor local fast_forward for
    select
        u.Email 
    from KenticoCMS1.dbo.AD_Advertise as a
        inner join KenticoCMS1.dbo.CMS_User as u on u.UserID = a.ItemCreatedBy 
    where
        a.AdShow = 1 and
        datediff(day, getdate(), a.AdDateTo) in 
        (
            select t.RemainDays
            from KenticoCMS1.dbo.AD_SendEmailForExpire as t
        )

open cur
while 1 = 1
begin
    fetch cur into @Email
    if @@fetch_status <> 0 break

    exec msdb.dbo.sp_send_dbmail
        @profile_name = 'ExpireAdvertiseEmail',
        @recipients = @Email,
        @subject = 'Test message',
        @body = 'This is the body of the test message.Congrates Database Mail Received By you Successfully.'      

end
close cur
deallocate cur

注意表别名,删除多余的括号。我认为删除datediff也有帮助,但之前必须查看你的数据。

答案 1 :(得分:0)

试试这个:把这个部分

while (  @i<=(select max(RowNumber) from cte))
BEGIN   
        @i=@i+1;
    EXEC msdb.dbo.sp_send_dbmail @profile_name='ExpireAdvertiseEmail',
    @recipients=  (

之前

with cte as

   )

...where RowNumber=@i

对于我的理解,cte定义必须直接跟随select(并且它只能用于后面的那个选择)

希望它有所帮助...

编辑:逗号显然是函数

的参数列表的一部分