2013-04-09 319 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;