1

我想创建一个表,然后在 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 ','.
4

2 回答 2

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,但必须先查看您的数据。

于 2013-09-14T13:40:36.640 回答
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 后面(它只能用于后面的一个 select)

希望能帮助到你...

编辑:逗号显然是函数参数列表的一部分

于 2013-09-14T13:26:39.227 回答