declaring cursor from a variable sql statement

Posted on 2004-11-29
Last Modified: 2012-06-27
I need to know if there is a way to declare a cursor from a variable sql statement, such as:

FROM < a table name that can be variable >

I was trying something like this:

DECLARE @TableName AS nvarchar(50)

SELECT @TableName = Name
FROM dbo.MyTables

EXEC('INSERT INTO #temp (fields1 integer, fields2 nvarchar(50), ...)
         SELECT *
         FROM ' + @TableName)

FROM #temp

But the problems is that I have to create the #temp table with the proper fields from a... variable table!!!
Question by:fbenve
    1 Comment
    LVL 68

    Accepted Solution

    You could use dynamic SQL, EXEC(...), as shown above, to create the table and declare the cursor.  However, AFAIK you cannot use dynamic SQL for a FETCH.  For the FETCH you will need to know specifically what columns are to be fetched.  You could use sp_executeSQL to get a variable set of columns from the table one row at a time, but that would be very slow.

    Featured Post

    Why You Should Analyze Threat Actor TTPs

    After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

    Join & Write a Comment

    Introduction SQL Server Integration Services can read XML files, that’s known by every BI developer.  (If you didn’t, don’t worry, I’m aiming this article at newcomers as well.) But how far can you go?  When does the XML Source component become …
    The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
    Viewers will learn how the fundamental information of how to create a table.
    Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

    729 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    17 Experts available now in Live!

    Get 1:1 Help Now