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

前端 未结 3 709
太阳男子
太阳男子 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:07

    Not possible, I made a script like it earlier.

    declare @searchvalue varchar(100)
    
    set nocount off
    
    set @searchvalue = 'Hello world'
    
    
    create table #tt (table_name varchar(64), column_name varchar(64), count int)
    select * into #t from 
    (
    select 'select ''' + a.table_name + ''' ''table_name'',''' + a.column_name + ''' ''column_name'', count(*) count from [' + a.table_name +'] where [' +a.column_name+']='''+@searchvalue +'''' + ' group by ['+ a.column_name+']' sqlstring
    from INFORMATION_SCHEMA.COLUMNS a
    join 
    INFORMATION_SCHEMA.TABLES b
    on a.table_name = b.table_name
    and b.table_type = 'base table'
     where data_type = 'varchar'
    ) a
    
    --loop cursor
    Declare @sqlstring as nvarchar(500)
    Declare SqlCursor CURSOR FAST_FORWARD FOR
    SELECT sqlstring FROM #t
    OPEN SqlCursor
    FETCH NEXT FROM SqlCursor
    INTO @sqlstring
    WHILE @@FETCH_STATUS = 0
    BEGIN
    insert #tt
    exec(@sqlstring)
         FETCH NEXT FROM SqlCursor
         INTO @sqlstring
    END
    CLOSE SqlCursor
    DEALLOCATE SqlCursor
    select * from #tt
    drop table #tt
    drop table #t
    

    Use what you want

    0 讨论(0)
  • 2021-01-19 20:08

    It's a loop or a function as you suggested (which is really a loop anyway).

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题