How do I dynamically set the table and field name in an update query?

前端 未结 3 1126
独厮守ぢ
独厮守ぢ 2021-01-24 01:37

I\'d like to loop over a list of tables. For each table, I\'d like to run an update query.

Psuedo code:

ArrayOfTablesObjects = {[\'tablename1\',\'fieldn         


        
3条回答
  •  星月不相逢
    2021-01-24 02:07

    You need to use dynamic SQL for this. The EXEC function will execute an ad-hoc sql statement passed in as a string.

    DECLARE @UpdateSql AS varchar(2000)
    
    foreach @tablename in ArrayOfTablesObjects 
    
    SET @UpdateSql = 'UPDATE ' + @tablename + ' SET ' + @fieldname ' + = ''xyz'' WHERE ' + @fieldname + ' = ''123'''
    EXEC (@UpdateSql)
    
    end foreach
    

提交回复
热议问题