title: Nested loop through databases in loop
body: <p>I have 4 the same databases</p>
  
  <pre><code>('User1','User2','User3','User4')
  </code></pre>
  
  <p>And a loop doing what it supposed to do:</p>
  
  <pre><code>DECLARE @json NVARCHAR(2000)
  DECLARE @getid CURSOR
  
  SET @getid = CURSOR FOR
  SELECT [custom_data] FROM [User1].[usr].[table] where [custom_data] like '%:true%' or [custom_data] like '%:false%'
  
  OPEN @getid
  FETCH NEXT
  FROM @getid INTO @json
  WHILE @@FETCH_STATUS = 0
  BEGIN
  SELECT JSON_MODIFY(@json, '$.field','value')
  FETCH NEXT FROM @getid INTO @json
  END
  
  CLOSE @getid
  DEALLOCATE @getid
  </code></pre>
  
  <p>My question is: How do I iterate through databases? I have tried to nest the loop containing variable with database name and then execute query in this way:</p>
  
  <p>First I:</p>
  
  <pre><code>DECLARE C CURSOR FOR SELECT name FROM sysdatabases WHERE name IN ('User1','User2','User3','User4')
  </code></pre>
  
  <p>as described in many examples and after that I wanted to concat db name into query and execue it like that:</p>
  
  <pre><code>DECLARE @dbname varchar(50)
  DECLARE C CURSOR FOR SELECT name FROM sysdatabases 
  WHERE name IN ('User1','User2','User3','User4')
  OPEN C
  WHILE @@FETCH_STATUS = 0
  BEGIN
  EXEC('DECLARE @json NVARCHAR(2000);
  DECLARE @getid CURSOR; SET @getid = CURSOR FOR SELECT [custom_data] FROM '+@dbName+'.[usr].[transactions]
  
  OPEN @getid;
  FETCH NEXT;
  FROM @getid INTO @json;
  WHILE @@FETCH_STATUS = 0;
  BEGIN;
  SELECT JSON_MODIFY(@json, ''$.Field'',''Value'');
  
  FETCH NEXT FROM @getid INTO @json
  END
  CLOSE @getid
  DEALLOCATE @getid')
  FETCH NEXT FROM C INTO @dbname
  END
  CLOSE C
  DEALLOCATE C
  </code></pre>
  
  <p>but it finishes loop with no errors with massage </p>
  
  <blockquote>
    <p>Commands completed successfully.</p>
  </blockquote>
  
  <p>but it changes nothing. I would appreciate your assistance</p>