How to use EXEC or sp_executeSQL without looping in this case?

前端 未结 3 710
太阳男子
太阳男子 2021-01-19 19:13

Environment: SQL Server 2005/2008, pubs database

I have inserted into a table variable a set of data as shown below using information

3条回答
  •  借酒劲吻你
    2021-01-19 20:10

    This is an old question, but I'd like to add a different answer all the same.

    Try the following script (no cursor, no loop (according to execution plan)): (tested in MS SQL 2012)

    -- Setting up test data/code    
    SELECT  N'SELECT * FROM INFORMATION_SCHEMA.COLUMNS AS C' T
    INTO    #Code
    UNION ALL
    SELECT  N'SELECT * FROM INFORMATION_SCHEMA.TABLES AS T'
    
    -- Variable to hold the selected queries, seperated by CrLf. You can also add a "GO" or ";"    
    DECLARE @SQL NVARCHAR(MAX) = CHAR(13) + CHAR(10)
    
    -- Concatenate the selected queries together into the variable
    SELECT  @SQL = @SQL + CHAR(13) + CHAR(10) + C.T
    FROM    #Code AS C
    
    -- Execute   
    EXEC sys.sp_executesql @SQL
    
    -- Clean up    
    DROP TABLE #Code
    

提交回复
热议问题