简体   繁体   中英

SQL WITH in WITH

I want to write a with in with SQL query.

Go some error. Please help:

DECLARE @Start AS DATETIME;
DECLARE @End AS DATETIME;
SET @Start = '2013-04-09';
SET @End = '2013-04-11';
with View_Solidnet_Training as 
(
with View_Solidnet_Training as
(
select  cast(@Start as datetime) DateValue
union all
select DateValue + 1
from View_Solidnet_Training
where DateValue + 1 <= cast(@End as datetime)
)
insert into OBJ_Availability  
select 34, DateValue, 'AM', 2, 'Test' from View_Solidnet_Training;
)
select * from View_Solidnet_Training where PK_Training_ID is not null;

error:

Msg 156, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'with'.
Msg 319, Level 15, State 1, Line 7
Incorrect syntax near the keyword 'with'. If this statement is a common table expression or an xmlnamespaces clause, the previous statement must be terminated with a semicolon.
Msg 102, Level 15, State 1, Line 17
Incorrect syntax near ')'.

Try this. This is just sample code. In this code , it is written the CTE withing CTE.

;with CTE1 as (
SELECT Patientid
,Lastname1
,age
,dob
,ROW_NUMBER() OVER (ORDER BY Patientid DESC) AS RowNumber
FROM PTN_PATIENT    
)
,CTE2 AS (
SELECT CTE1.Patientid
,CTE1.Lastname1
,CTE1.age
,CTE1.dob
,CTE1.RowNumber
,DATEDIFF(YEAR,CTE1.dob,GETDATE()) as yearOfservce
FROM Lab_LabDiagOrder INNER JOIN CTE1
ON Lab_LabDiagOrder.Patientid = CTE1.Patientid
WHERE CTE1.RowNumber between 1 and 5
)
SELECT * FROM CTE2;

You cannot have DECLARE and SET inside a CTE (Common Table Expression).

DECLARE @Start AS DATETIME;
DECLARE @End AS DATETIME;
SET @Start = '2013-04-09';
SET @End = '2013-04-11';

;WITH View_Solidnet_Training AS
(
    SELECT @Start AS DateValue

    UNION ALL

    SELECT DateValue + 1
    FROM View_Solidnet_Training
    WHERE DateValue + 1 <= @End 
)
SELECT
    34, DateValue, 'AM', 2, 'Test' 
FROM 
    View_Solidnet_Training
-- WHERE 
--    PK_Training_ID IS NOT NULL

I don't know where that PK_Training_ID is supposed to come from - it's nowhere to be found in your code.....

Notes:

  • you cannot have DECLARE and SET inside a CTE - only SELECT and UNION ALL
  • the @Start and @End are already declared as DATETIME - there's absolutely no point in casting those to DATETIME again ....
  • the values from the CTE are available right after the CTE, for exactly one T-SQL statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM