title: How to dynamically select tables and columns in SQL Server?
body: <p>I am trying to create a <code>SQL code</code> in <code>SQL Server</code> that dynamically selects all the tables in a specific database and then for each column in each table, counts the number of missing values and non-null values. I also want this result inserted into another table. </p>
  
  <p>Is there any way I can do this without manually changing the column names for each:</p>
  
  <p><code>Table Name - Column selection</code></p>
  
  <p>I have a teradata code for the same which I tried to convert to <code>SQL Server code</code>. But I am unable to get the dynamic allocation and insertion parts right.</p>
  
  <pre><code>insert into temp
  values (select  ''CAMP'',
      rtrim(''' || tablename || '''),
      rtrim(''' || columnname || '''),
      rtrim(''' || columnformat || '''),
      count(1),
      count(rtrim(upper(case when ' || columnname || '='''' then NULL else '|| columnname ||' end))),
      (cast (count(rtrim(upper(case when  ' || columnname || '='''' then NULL else  ' || columnname || ' end))) as float) / (cast (count(1) as float))) * 100,
      count(distinct rtrim(upper(case when ' || columnname || '='''' then NULL else '|| columnname ||' end))),
      min(rtrim(upper(case when ' || columnname || '='''' then NULL else '|| columnname ||' end))),
      max(rtrim(upper(case when ' || columnname || '='''' then NULL else '|| columnname ||' end))),
      min(len(rtrim(upper(case when ' || columnname || '='''' then NULL else '|| columnname ||' end)))),
      max(len(rtrim(upper(case when ' || columnname || '='''' then NULL else '|| columnname ||' end))))
  from    ' || tablename ||')
  </code></pre>
  
  <p>Any help on this front would be great!
  Thanks!</p>