用查询结果填充临时表时出错

时间:2019-02-21 16:20:16

标签: sql tsql syntax-error temp

为什么这个查询单独运行好,但是当我尝试将结果放入临时表时却出现错误

作品

SELECT DISTINCT
ENCOUNTER_ID        = OP.PAT_ENC_CSN_ID
,NOTE_TYPE          = OP.PROC_CODE
,CREATE_TIME        = OP.ORDER_INST
,OP.ORDER_PROC_ID
,EAP.PROC_NAME
-----INTO #ECHO_ORDERS
FROM PAT_ENC E 
INNER JOIN #SER SER ON SER.PROV_ID = E.VISIT_PROV_ID
INNER JOIN ORDER_PROC OP ON OP.PAT_ENC_CSN_ID = E.PAT_ENC_CSN_ID
INNER JOIN CLARITY_EAP EAP  ON EAP.PROC_ID = OP.PROC_ID
INNER JOIN EDP_PROC_CAT_INFO EDP ON EDP.PROC_CAT_ID = EAP.PROC_CAT_ID
WHERE (EAP.PROC_NAME LIKE '%ECHO%' 
OR EDP.PROC_CAT_NAME LIKE 'ECH%')
AND EDP.PROC_CAT_NAME NOT IN ( 'CHG LABORATORY',    'LAB BLOOD ORDERABLES', 'PR GASTROENTEROLOGY',  'PR INJECTABLE MEDS',   'URINE ORDERABLES')

不起作用

if object_id('tempdb..#ECHO_ORDERS') is not null  begin drop table #ECHO_ORDERS
SELECT DISTINCT
ENCOUNTER_ID        = OP.PAT_ENC_CSN_ID
,NOTE_TYPE          = OP.PROC_CODE
,CREATE_TIME        = OP.ORDER_INST
,OP.ORDER_PROC_ID
,EAP.PROC_NAME
INTO #ECHO_ORDERS
FROM PAT_ENC E 
INNER JOIN #SER SER ON SER.PROV_ID = E.VISIT_PROV_ID
INNER JOIN ORDER_PROC OP ON OP.PAT_ENC_CSN_ID = E.PAT_ENC_CSN_ID
INNER JOIN CLARITY_EAP EAP  ON EAP.PROC_ID = OP.PROC_ID
INNER JOIN EDP_PROC_CAT_INFO EDP ON EDP.PROC_CAT_ID = EAP.PROC_CAT_ID
WHERE (EAP.PROC_NAME LIKE '%ECHO%' 
OR EDP.PROC_CAT_NAME LIKE 'ECH%')
AND EDP.PROC_CAT_NAME NOT IN ( 'CHG LABORATORY',    'LAB BLOOD ORDERABLES', 'PR GASTROENTEROLOGY',  'PR INJECTABLE MEDS',   'URINE ORDERABLES')

当我运行不起作用的代码时,我收到关于最后一行代码的错误消息

Msg 102, Level 15, State 1, Line 222
Incorrect syntax near ')'.

1 个答案:

答案 0 :(得分:0)

如果您正确设置代码格式,则很清楚为什么代码无法正常工作。

if object_id('tempdb..#ECHO_ORDERS') is not null  
begin 
    drop table #ECHO_ORDERS

    SELECT DISTINCT
        ENCOUNTER_ID        = OP.PAT_ENC_CSN_ID
        ,NOTE_TYPE          = OP.PROC_CODE
        ,CREATE_TIME        = OP.ORDER_INST
        ,OP.ORDER_PROC_ID
        ,EAP.PROC_NAME
    INTO #ECHO_ORDERS
    FROM PAT_ENC E 
    INNER JOIN #SER SER ON SER.PROV_ID = E.VISIT_PROV_ID
    INNER JOIN ORDER_PROC OP ON OP.PAT_ENC_CSN_ID = E.PAT_ENC_CSN_ID
    INNER JOIN CLARITY_EAP EAP  ON EAP.PROC_ID = OP.PROC_ID
    INNER JOIN EDP_PROC_CAT_INFO EDP ON EDP.PROC_CAT_ID = EAP.PROC_CAT_ID
    WHERE (EAP.PROC_NAME LIKE '%ECHO%' OR EDP.PROC_CAT_NAME LIKE 'ECH%')
        AND EDP.PROC_CAT_NAME NOT IN ( 
            'CHG LABORATORY',    'LAB BLOOD ORDERABLES', 'PR GASTROENTEROLOGY',  'PR INJECTABLE MEDS',   'URINE ORDERABLES'
        )

您有BEGIN,没有END