How can I use if statement after a CTE (SQL Server 2005)

前端 未结 4 596
无人共我
无人共我 2020-12-29 04:12

Last night I was writing a simple T-SQL program something like this

DECLARE @ROLEID AS INT

SELECT @ROLEID = [ROLE ID] FROM TBLROLE

;WITH CTE
AS
( 
    SELE         


        
相关标签:
4条回答
  • 2020-12-29 04:17

    The closest you'll get is using a UNION ALL to do a crude switched select:

    DECLARE @ROLEID AS INT
    
    SELECT @ROLEID = [ROLE ID] FROM TBLROLE
    
    ;WITH CTE
    AS
    ( 
        SELECT * FROM SOMETABLE
    )
    SELECT
        --somecolumns
    FROM
        CTE
        --other stuff too
    WHERE
        @ROLEID = 1
    UNION ALL
    SELECT
        --somecolumns
    FROM
        CTE
        --other stuff too
    WHERE
        @ROLEID = 2
    UNION ALL
    SELECT
        --somecolumns
    FROM
        CTE
        --other stuff too
    WHERE
        @ROLEID = 3
    ...
    UNION ALL
    SELECT
        --somecolumns
    FROM
        CTE
        --other stuff too
    WHERE
        @ROLEID = n
    
    0 讨论(0)
  • 2020-12-29 04:20

    A little late but I can't be the only one bumping into this.

    A solution could be to create a temporary table like this:

    -- If previous run of this query fails, the temp table will be deleted.
    -- Selecting into creates the temp table which fails if it already exists
    IF EXISTS(SELECT [name] FROM tempdb.sys.tables WHERE [name] like '#dtBalansOpgesteldGefilterd%') BEGIN
       DROP TABLE #temp
    END;
    
    ;WITH CTE
    AS
    ( 
        SELECT * FROM SOMETABLE
    )
    
    -- Followed by select statement as required
    SELECT *
    INTO #temp
    FROM CTE
    
    IF @awsome = 1
    BEGIN
        SELECT 'WHATEVERYOUWANT' AS WhateverColumnNameYouWant, *
        FROM #temp
    END
    
    0 讨论(0)
  • 2020-12-29 04:29

    Common table expressions are defined within the context of a single statement:

    WITH cte_name AS (
      <cte definition>)
    <statement that uses cte>;
    

    So you can do something like:

    WITH CTE
    AS
    ( 
        SELECT * FROM SOMETABLE
    )
    SELECT * FROM CTE;
    

    or

    WITH CTE
    AS
    ( 
        SELECT * FROM SOMETABLE
    )
    UPDATE CTE 
    SET somefield = somevalue
    WHERE id = somekey;
    

    A CTE must be followed by a single SELECT, INSERT, UPDATE, MERGE, or DELETE statement that references some or all the CTE columns. A CTE can also be specified in a CREATE VIEW statement as part of the defining SELECT statement of the view

    0 讨论(0)
  • 2020-12-29 04:36

    Try putting the CTE in the IF. It worked for me.

    IF @awsome = 1
    BEGIN
    ;WITH CTE
    AS
    ( 
        SELECT * FROM SOMETABLE
    )
        SELECT 'WHATEVERYOUWANT' FROM CTE
    END
    ELSE IF @awesome = 2
    BEGIN
    ;WITH CTE2
    AS
    ( 
        SELECT * FROM SOMETABLE
    )
        SELECT 'WHATEVERYOUWANT' FROM CTE2
    END
    
    0 讨论(0)
提交回复
热议问题