• Yasemin Örnek (9/19/2012)


    Hi , I want to ask a question ,

    Is it possible executing dynamic sql and store values in a temp table with WITH clause like below code?

    DECLARE @sqltxt nvarchar(max) ;

    SET @sqltxt='select col112,col221 from sometable';

    WITH temptable (col1,col2) as

    (exec sp_executesql @sqltxt )

    select * from temptable

    Or how can I achive this task with sql?

    Thanks.

    First of all, you shouldn't hijack other peoples' threads when you can easily start a new one of your own. Secondly, I shouldn't encourage you in doing so by answering your questions. 🙂

    But since I answered before realizing this, I'll say I'm pretty sure that your syntax will not work. Try it!

    You could try do something like this:

    DECLARE @sqltxt nvarchar(max) ;

    SET @sqltxt='INSERT INTO temptable (col1,col2) select col112,col221 from sometable';

    exec sp_executesql @sqltxt

    select * from temptable

    That will work with permanent or temporary tables, but not table variables (they will not be in the context of the executed dynamic SQL).


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St