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 を続ける必要があります (そして、それに続く 1 つの select でのみ使用できます)。

それが役に立てば幸い...

編集:カンマは明らかに関数のパラメータリストの一部です

于 2013-09-14T13:26:39.227 に答える