2013-04-09 163 views
0

我想用SQL查詢編寫一個。SQL WITH WITH

出現一些錯誤。請幫助:

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; 

錯誤:

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 ')'.

+1

你到底想幹什麼?!?!?你**不能**在CTE內部有'DECLARE'和'SET',並且你**不能**將CTE插入到另一個表中。請用簡單的英語解釋**您正在嘗試做什麼..... – 2013-04-09 09:23:17

+1

Marc是正確的 - 您的示例查詢有太多的錯誤讓我們看到您想要實現的目標。也許如果你解釋你的表格結構以及你想從中得到什麼,這會有所幫助。 – 2013-04-09 09:25:43

+0

我已經改變了一點。但是我必須將數據從視圖中插入到表格中。中間'與'完美。它在表格中插入行。但在SSIS中,此解決方案僅適用於視圖中的一行。所以我需要做一個循環來檢查視圖的ID是否爲零,它必須聲明新的日期並插入視圖的下一行。 – user2206834 2013-04-09 09:29:49

回答

0

你不能DECLARESET的CTE(公共表表達式)內。

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 

我不知道那裏PK_Training_ID是從何而來 - 它遠不在你的代碼被發現.....

注:

  • 你不能有DECLARESET內CTE - 只有SELECTUNION ALL
  • @Start@End已被聲明爲DATETIME - 但絕對鑄造那些DATETIME再沒有一點....是
  • 從CTE值可用的CTE之後,整整一個T-SQL語句
1

試試這個。這只是示例代碼。在這個代碼中,它是用CTE編寫的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;