title: SQL Server - Using JSON to return Column Names
body: <p>I have the following test query I'm needing to make dynamic.</p>
  
  <p>Basically a stored procedure will be passed @json and it needs to return the column names that are passed in that variable.</p>
  
  <p>Is this possible and how could I do it?</p>
  
  <pre><code>declare @json varchar(max)
  
  set @json = '["FirstName", "LastName","DOB"]';  
  
  select *   
  from OPENJSON( @json )  
  
  select
  FirstName,
  LastName,
  DOB
  from Client
  </code></pre>
  
  <p>I do have this that works, but not sure on whether it's a good option and whether there's a better way</p>
  
  <pre><code>declare @json varchar(max)
  declare @columnames varchar (200)
  declare @sqlquery nvarchar(200)
  
  set @json = '["FirstName", "LastName","DOB"]';  
  set @columnames =''
  
  select @columnames = 
      case when @columnames = ''
      then value
      else @columnames + coalesce(',' + value, '')
      end
    from OPENJSON( @json )  
  
  set  @sqlquery = 'select ' + @columnames + ' from Client'
  
  EXEC SP_EXECUTESQL @sqlquery
  </code></pre>
  
  <p>Basically the @json variable can contain one or many or all of the below fields and over-time even more. </p>
  
  <pre><code>set @json = '["FirstName", "LastName","DOB","DrugName,"Age","AgeGroup","Overdose","VerificationCode","Gender"]'; 
  </code></pre>