使用 CTE 填充 table 变量
Fill a table variable using CTE
我正在创建一个 CTE,因为我需要一个变量中的所有 InquiryId 才能继续进行 WHILE 循环。
我正在尝试通过如下所示的 CTE 填充变量
DECLARE @inqIdsToClose TABLE (InquiryId int)
With CTE (InquiryId,InquirySubject,CreateDt,SendTo,[From],SendBy) as
(
Select I.InquiryId,I.InquirySubject,I.CreateDt,I.SendTo,I.[From],U.Email as SendBy
From Inquiries I
Inner Join Users U
ON I.[From] = U.UserID
Where I.InquiryId Not In (Select InquiryId from InquiryReply)
And I.InquiryStatusId <> 5
And DATEDIFF(day, I.CreateDt, getdate()) >=7
)
Insert into @inqIdsToClose
Select InquiryId from CTE
Print @inqIdsToClose;
但是SQL服务器不允许我填写@inqIdsToClose
CTE 返回的 InquiryId 是多个,稍后我将在 while 循环中使用。
声明 table 变量后缺少终止符
例子
DECLARE @inqIdsToClose TABLE (InquiryId int);
with cte as (
-- Dummy query
Select SomeVal=1
Union All
Select SomeVal=2
)
Insert Into @inqIdsToClose Select SomeVal from cte
Select * from @inqIdsToClose
Returns
InquiryId
1
2
我正在创建一个 CTE,因为我需要一个变量中的所有 InquiryId 才能继续进行 WHILE 循环。 我正在尝试通过如下所示的 CTE 填充变量
DECLARE @inqIdsToClose TABLE (InquiryId int)
With CTE (InquiryId,InquirySubject,CreateDt,SendTo,[From],SendBy) as
(
Select I.InquiryId,I.InquirySubject,I.CreateDt,I.SendTo,I.[From],U.Email as SendBy
From Inquiries I
Inner Join Users U
ON I.[From] = U.UserID
Where I.InquiryId Not In (Select InquiryId from InquiryReply)
And I.InquiryStatusId <> 5
And DATEDIFF(day, I.CreateDt, getdate()) >=7
)
Insert into @inqIdsToClose
Select InquiryId from CTE
Print @inqIdsToClose;
但是SQL服务器不允许我填写@inqIdsToClose
CTE 返回的 InquiryId 是多个,稍后我将在 while 循环中使用。
声明 table 变量后缺少终止符
例子
DECLARE @inqIdsToClose TABLE (InquiryId int);
with cte as (
-- Dummy query
Select SomeVal=1
Union All
Select SomeVal=2
)
Insert Into @inqIdsToClose Select SomeVal from cte
Select * from @inqIdsToClose
Returns
InquiryId
1
2