我在将cte值插入表时遇到错误

时间:2017-05-15 19:35:01

标签: sql-server

INSERT INTO CLEANUP.DBO.TMP_CLAIM_PBI33562_2 (NCLAIMID, SATTYFILENO, DTLASTPMT, ACTUALPMTDATE, SWORKSTATIONID, DTCHANGEDON, NCHANGEDBY, NAPPLICATIONID)
; WITH LST_CTE AS 
(
    SELECT 
        NCLAIMID, MAX(DTTRANSACTION) AS ACTUALPMTDATE 
    FROM 
        CLAIMREGISTRY 
    WHERE 
        NTRANLINKID IS NULL
        AND NTRANSACTIONCODEID IN (1,13)
    GROUP BY 
        NCLAIMID
) 

SELECT 
    C.NCLAIMID, C.SATTYFILENO, C.DTLASTPMT,
    L.ACTUALPMTDATE, C.SWORKSTATIONID, C.DTCHANGEDON,
    C.NCHANGEDBY, C.NAPPLICATIONID
FROM 
    CLAIM AS C
JOIN 
    LST_CTE AS L ON L.NCLAIMID = C.NCLAIMID
WHERE 
    CONVERT(VARCHAR, C.DTLASTPMT, 112) <> CONVERT(VARCHAR, L.ACTUALPMTDATE, 112)

2 个答案:

答案 0 :(得分:2)

withinsert之前。 。 。并且声明中间没有分号:

WITH LST_CTE AS (
    SELECT NCLAIMID,MAX(DTTRANSACTION) AS ACTUALPMTDATE FROM CLAIMREGISTRY 
    WHERE NTRANLINKID IS NULL
    AND NTRANSACTIONCODEID IN (1,13)
    GROUP BY NCLAIMID
) 
insert into CLEANUP.DBO.TMP_CLAIM_PBI33562_2 (NCLAIMID, SATTYFILENO,DTLASTPMT,ACTUALPMTDATE,SWORKSTATIONID,DTCHANGEDON,NCHANGEDBY,NAPPLICATIONID)
    SELECT C.NCLAIMID, C.SATTYFILENO,C.DTLASTPMT,L.ACTUALPMTDATE,c.SWORKSTATIONID,c.DTCHANGEDON,c.NCHANGEDBY,c.NAPPLICATIONID
    FROM CLAIM C JOIN
         LST_CTE L 
         ON L.NCLAIMID = C.NCLAIMID
    WHERE CONVERT(VARCHAR(255), C.DTLASTPMT, 112) <> CONVERT(VARCHAR(255), L.ACTUALPMTDATE, 112);

我也不喜欢WHERE条款。如果您只想比较日期,请比较日期:

WHERE CAST(C.DTLASTPMT as DATE) = CAST(L.ACTUALPMTDATE as DATE)

为什么要转换为字符串来比较日期?

答案 1 :(得分:1)

首先尝试声明cte

;with LST_CTE as (
  select NCLAIMID
   , MAX(DTTRANSACTION) as ACTUALPMTDATE
  from CLAIMREGISTRY
  where NTRANLINKID is null and NTRANSACTIONCODEID in (1, 13)
  group by NCLAIMID
 )
insert into CLEANUP.DBO.TMP_CLAIM_PBI33562_2 (
 NCLAIMID
 , SATTYFILENO
 , DTLASTPMT
 , ACTUALPMTDATE
 , SWORKSTATIONID
 , DTCHANGEDON
 , NCHANGEDBY
 , NAPPLICATIONID
 )
select C.NCLAIMID
 , C.SATTYFILENO
 , C.DTLASTPMT
 , L.ACTUALPMTDATE
 , c.SWORKSTATIONID
 , c.DTCHANGEDON
 , c.NCHANGEDBY
 , c.NAPPLICATIONID
from CLAIM as C
  inner join LST_CTE as L 
    on L.NCLAIMID = C.NCLAIMID
where CONVERT(varchar(30), C.DTLASTPMT, 112) <> CONVERT(varchar(30), L.ACTUALPMTDATE, 112)

此外,如果DTLASTPMTACTUALPMTDATEdatedatetime数据类型,则您无需convert()对其进行比较。