Nest With statement errors

时间:2018-06-04 17:02:12

标签: nested

I'm trying to use WITH statements and getting errors and I'm hoping someone can help. I'm querying a database of logged calls; the table with the call details doesn't have the details of the caller, that's in a separate table, and the call can have one (or more) callers associated with it, or none - in which case there will be a company name. And I still want the call details even when there's none, but if we have those details, I want them; I'm having to look for 'AD-User' in the row in the second table where the call numbers match.

I've got this:

WITH AllCompanysCalls as

(
     SELECT [RSUPDESK].[dbo].[Request].ID as CallID  
     ,[dbo].[vw_Associations].Item   

     FROM [RSUPDESK].[dbo].[Request]
     Inner Join  [RSUPDESK].[dbo].[vw_Associations]  ON [RSUPDESK].[dbo].[Request].ID = [RSUPDESK].[dbo].[vw_Associations].RQID 
     WHERE  ([RSUPDESK].[dbo].[vw_Associations].PrimaryAssociation = '1' and [RSUPDESK].[dbo].[vw_Associations].Item = 'Bob The Builder') 
     AND DATEPART(m, LoggedDate) = DATEPART(m, DATEADD(m, -1, getdate()))
     AND DATEPART(yyyy, LoggedDate) = DATEPART(yyyy, DATEADD(m, -1, getdate()))
)
,

WITH CallsWithUser AS

(
    SELECT CallID     
    ,[vw_Associations].[Item] as Username
    ,[vw_Associations].Style

    FROM AllCompanysCalls  Join  [RSUPDESK].[dbo].[vw_Associations]  ON AllCompanysCalls.CallID = [RSUPDESK].[dbo].[vw_Associations].RQID 
    WHERE [RSUPDESK].[dbo].[vw_Associations].Style = 'Contact'
 )
 ,

SELECT  AllCompanysCalls.CallID      
,CallsWithUser.[vw_Associations].[Item] as Username

FROM AllCompanysCalls LEFT Join  CallsWithUser  ON AllCompanysCalls.CallID = CallsWithUser.CallID 

Sorry it's a mess, but I can't see any other way of doing it.

THis is the error I'm getting:

Msg 156, Level 15, State 1, Line 76 Incorrect syntax near the keyword 'WITH'. Msg 319, Level 15, State 1, Line 76 Incorrect syntax near the keyword 'with'. If this statement is a common table expression, an xmlnamespaces clause or a change tracking context clause, the previous statement must be terminated with a semicolon. Msg 102, Level 15, State 1, Line 145 Incorrect syntax near ','.

Can anyone help please? it's clearly to do with having multiple with statements and the second uses the results of the first, but I can't work it out.

0 个答案:

没有答案