I have the following test query I'm needing to make dynamic.
Basically a stored procedure will be passed @json and it needs to return the column names that are passed in that variable.
Is this possible and how could I do it?
declare @json varchar(max)
set @json = '["FirstName", "LastName","DOB"]';
select *
from OPENJSON( @json )
select
FirstName,
LastName,
DOB
from Client
I do have this that works, but not sure on whether it's a good option and whether there's a better way
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
Basically the @json variable can contain one or many or all of the below fields and over-time even more.
set @json = '["FirstName", "LastName","DOB","DrugName,"Age","AgeGroup","Overdose","VerificationCode","Gender"]';
SELECT field1,field2,field3 FROM Table(i.e. every field). Then inside the application it decides (based on your user selection) what is actually shown. That's what I mean by parsed. There is probably more to this than you've explained though.