简体   繁体   中英

Loop on query with parameters coming from variables

I need to perform a set of queries to extract the distinct values of a group of fields from different tables, so far I managed to create the cursor that makes the loop as expected, but I'm not able to create the query in the loop assigning the values as I need. please look at below example:

DECLARE    @sourcetablename NVARCHAR(250),
           @targettablename NVARCHAR(250),
           @sourcefieldname NVARCHAR(250);

DECLARE DMTCursor CURSOR FOR
    
    SELECT
    SOURCETABLE, TARGETTABLE, ENTITYFIELD 
    FROM  DMTSOURCE ;
      
OPEN DMTCursor ;

FETCH NEXT FROM DMTCursor INTO
@sourcetablename,
@targettablename,
@sourcefieldname;

WHILE @@FETCH_STATUS = 0
BEGIN

      PRINT @sourcetablename + ' ' + @targettablename+ ' ' + @sourcefieldname;

      FETCH NEXT FROM DMTCursor INTO
        @sourcetablename,
        @targettablename,
        @sourcefieldname;
END;

CLOSE DMTCursor ;

DEALLOCATE DMTCursor ;

in this example I used a print function to test the code and it actually shows the values that I want to use as parameters for the query, but I cannot figure out how to use them in the select, let's make for instance that the first row coming from the cursor retrieves:

@sourcetablename = sourcetable1
@targettablename = targettable1
@sourcefieldname = sourcefield1

I want the loop query (replacing the PRINT line) be like:

 select distinct
     'targettable1' AS ENTITY,
     'sourcefield1' AS SOURCE_FIELD,
      sourcefield1 AS DISTINCTVALUE
      from    targettable1

just replacing the variables in the query does not work, it shows the error about the table (targettable1) not declared as a variable and I need a way to set the first 2 parameters as "fixed" strings (that's why I wrote them among '' in above example) in the query.

thanks in advance for help,

thanks shawnnt00, Dynamic sql helped me to figure out the SELECT inside the loop:

SET @SQL=N'
    select distinct ''' +
     @targettablename + ''' AS ENTITY, ''' +
     @sourcefieldname + ''' AS SOURCE_FIELD, ' +
     @sourcefieldname + ' AS VALUE
      from '          +  @targettablename ;
EXEC sp_executesql @SQL;

the point of discussion was not about the cursor but just on the parameters management, thanks everybody for support

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM