存储过程中的CTE无法正常工作

时间:2013-08-02 18:47:21

标签: sql stored-procedures common-table-expression

我有一个存储过程正在构建表以便稍后在查询中调用。我不得不添加使用CTE的新表,但是现在当我用它运行它时;结束表达式,我收到错误';'附近的语法不正确当我删除它时,我收到了我需要的错误;用CTE。查询本身在存储过程之外工作。任何帮助将不胜感激....

set @cdq = 'insert #REMOVAL_FLAG
(
    MYKEY,
    REMOVAL_FLAG
)

    WITH 
create_key AS(
        SELECT *,
        (CONVERT(varchar(25), a.NDC11, 101) + CONVERT(varchar(25), a.PharmacyID, 101) + CONVERT(varchar(50),ABS(a.TotalNetCost),101)) as REVERSAL_KEY

        FROM table1 a

),

find_rev AS (

        SELECT *,
            CASE
                WHEN MIN(TotalAmount) OVER (PARTITION BY REVERSAL_KEY) < 0 THEN 1 ELSE NULL
            END as Flag

        FROM create_key

),

primary_flag as (

        SELECT TOP 1500000 *,
            DENSE_RANK() OVER (ORDER BY REVERSAL_KEY) as [GROUP],
            ROW_NUMBER() OVER (PARTITION BY NDC11, PharmacyID, TotalNetCost ORDER BY REVERSAL_KEY) as PK

        FROM find_rev

        WHERE Flag = 1

        ORDER BY [GROUP], PK
),

flagged as (
        SELECT *,
            CASE
                WHEN COUNT (PK) OVER (PARTITION BY [GROUP], PK) > 1 THEN ''REMOVE''
            END as REMOVAL_FLAG

        FROM primary_flag
)

SELECT a1.MYKEY, f.REMOVAL_FLAG

FROM table1 a1
LEFT OUTER JOIN flagged f ON (f.MYKEY = a1.MYKEY)


'

1 个答案:

答案 0 :(得分:1)

insert语句可以使用CTE(with表达式)。在SQL Server中,这是之前的 insert,而不是select之前的

WITH 
create_key AS(
        SELECT *,
        (CONVERT(varchar(25), a.NDC11, 101) + CONVERT(varchar(25), a.PharmacyID, 101) + CONVERT(varchar(50),ABS(a.TotalNetCost),101)) as REVERSAL_KEY

        FROM table1 a

),
find_rev AS (
        SELECT *,
            CASE
                WHEN MIN(TotalAmount) OVER (PARTITION BY REVERSAL_KEY) < 0 THEN 1 ELSE NULL
            END as Flag
        FROM create_key
),
primary_flag as (

        SELECT TOP 1500000 *,
            DENSE_RANK() OVER (ORDER BY REVERSAL_KEY) as [GROUP],
            ROW_NUMBER() OVER (PARTITION BY NDC11, PharmacyID, TotalNetCost ORDER BY REVERSAL_KEY) as PK
        FROM find_rev
        WHERE Flag = 1
        ORDER BY [GROUP], PK
),
flagged as (
        SELECT *,
            CASE
                WHEN COUNT (PK) OVER (PARTITION BY [GROUP], PK) > 1 THEN ''REMOVE''
            END as REMOVAL_FLAG
        FROM primary_flag
)
insert #REMOVAL_FLAG(MYKEY, REMOVAL_FLAG)
    SELECT a1.MYKEY, f.REMOVAL_FLAG
    FROM table1 a1
    LEFT OUTER JOIN flagged f ON (f.MYKEY = a1.MYKEY)