我正在尝试运行一个SQL查询,其中包含一个MERGE INTO语句,它循环遍历每个月。
我收到了一些语法错误:
Msg 156,Level 15,State 1,Line 3关键字'INTO'附近的语法不正确。
消息156,级别15,状态1,行10关键字“AS”附近的语法不正确。
Msg 102,Level 15,State 1,Line 35','。附近的语法不正确。
正确打印月份/年,所以我认为问题不在循环中,而是在合并语句中。我环顾四周,但它看起来对我来说,但我确信我错过了一些东西。我本来可以发誓我之前使用过这段代码而且工作正常。
以下是代码:
Declare @StartDate As Datetime set @StartDate = '5/1/2015'; --Update to first month that needs to be added
Declare @StopDate As Datetime set @StopDate = '12/1/2015'; --Update to last month that needs to be added
Print 'Start Date ' + Cast(@StartDate as varchar(30));
Print 'Stop Date ' + Cast(@StopDate as varchar(30));
Print 'Total Months ' + Cast(Datediff(Month, @StartDate, @StopDate) + 1 as varchar(30));
Print ' ';
Declare @Date As Datetime set @Date = @StartDate;
Declare @SQL_Cmd As Varchar(Max);
Declare @SQL_Contract_Status As Varchar(Max) set @SQL_Contract_Status =
'
MERGE
INTO ANNUSER1.RPS_Contract_Person_PT AS TGT
USING ( Select
P.Datamart_Timestamp
,P.Contract_ID
,P.DOB
,Ltrim(Rtrim(
CASE
WHEN P.Datamart_Timestamp
< CONVERT(DATETIME, ''2007-06-01 00:00:00'', 102)
AND Len(P.Name_Last) > 25
THEN Substring(P.Name_Last,26,Len(P.Name_Last)-25)
ELSE P.Name_First
END)) As Name_First
,Ltrim(Rtrim(
CASE
WHEN P.Datamart_Timestamp
< CONVERT(DATETIME, ''2007-06-01 00:00:00'', 102)
AND Len(P.Name_Last) > 25
THEN LTrim(Left(P.Name_Last,25))
ELSE P.Name_Last
END)) As Name_Last
,P.Sex
,P.TIN
,P.TIN_Type
,D.Group_Plan_ID
From AT_RPS_2015_05_Contract_Person AS P
INNER JOIN AT_RPS_2015_05_Contract_Data AS D
ON P.Contract_ID = D.Contract_ID
WHERE (P.[Role] IN (''PT''))
) AS SRC
ON ( TGT.Contract_ID = SRC.Contract_ID )
AND ( TGT.DOB = Cast(SRC.DOB as Date)
OR ( TGT.DOB IS NULL
AND SRC.DOB IS NULL ) )
AND ( TGT.Name_First = SRC.Name_First
OR ( TGT.Name_First IS NULL
AND SRC.Name_First IS NULL ) )
AND ( TGT.Name_Last = SRC.Name_Last
OR ( TGT.Name_Last IS NULL
AND SRC.Name_Last IS NULL ) )
AND ( TGT.Sex = SRC.Sex
OR ( TGT.Sex IS NULL
AND SRC.Sex IS NULL ) )
AND ( TGT.TIN = SRC.TIN
OR ( TGT.TIN IS NULL
AND SRC.TIN IS NULL ) )
AND ( TGT.TIN_Type = SRC.TIN_Type
OR ( TGT.TIN_Type IS NULL
AND SRC.TIN_Type IS NULL ) )
WHEN NOT MATCHED
THEN
INSERT
(
Contract_ID
,Sequence_Number
,DOB
,Name_First
,Name_Last
,Sex
,TIN
,TIN_Type
,Datamart_Timestamp
,Group_Plan_ID
)
VALUES
(
SRC.Contract_ID
,Coalesce(
(SELECT Max(Sequence_Number)
FROM ANNUSER1.RPS_Contract_Person_PT AS TGT
WHERE TGT.Contract_ID = SRC.Contract_ID)
,0) + 1
,Cast(SRC.DOB as Datetime)
,SRC.Name_First
,SRC.Name_Last
,SRC.Sex
,SRC.TIN
,SRC.TIN_Type
,Cast(SRC.Datamart_Timestamp As Datetime)
,SRC.Group_Plan_ID
); ';
While @Date <= @StopDate
Begin
Set @SQL_Cmd = Replace(Replace(@SQL_Contract_Status, 'YYYY', Year(@Date)), 'MM', Right('0' + Cast(Month(@Date) As Varchar(2)), 2));
Exec (@SQL_Cmd);
Print Cast(Year(@Date) as varchar(30)) + '_' + Right('0' + Cast(Month(@Date) as varchar(30)),2) + ' ' + Cast(@@RowCount as varchar(30));
Set @Date = Dateadd(Month, 1, @date);
End;
GO