我有以下测试查询,我需要动态。
基本上,存储过程将传递给@json,它需要返回在该变量中传递的列名。
这可能吗?我怎么能这样做?
declare @json varchar(max)
set @json = '["FirstName", "LastName","DOB"]';
select *
from OPENJSON( @json )
select
FirstName,
LastName,
DOB
from Client
我确实有这个有效,但不确定它是否是一个好的选择以及是否有更好的方法
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
基本上,@ json变量可以包含以下字段中的一个或多个或全部,并且可以包含更多时间。
set @json = '["FirstName", "LastName","DOB","DrugName,"Age","AgeGroup","Overdose","VerificationCode","Gender"]';
答案 0 :(得分:0)
在这种情况下(您的json字符串仅包含带有列名称的标题)并仅用于列选择,因此很容易。如果你想从json字符串中获取值,那就更难了。
变体1:使用系统表验证输入并获取列名。
declare @json varchar(800) = '["FirstName", "LastName", "DOB","DrugName,"Age","AgeGroup", "Overdose","VerificationCode","Gender"]',
@columnames varchar(800)
select @columnames = isnull(@sql + ', ', name) + name
from (
select name, '"' + name + '"' name_quoted
from sys.columns c
where object_id('dbo.Client') = object_id) t
where @json like '%' + name_quoted + '%'
print @columnames
exec ('select ' + @columnames + ' from dbo.Client')
变体2:使用字符串。
declare @json varchar(800) = '["FirstName", "LastName","DOB","DrugName,"Age","AgeGroup","Overdose","VerificationCode","Gender"]';
declare @sql varchar(max) = replace(substring(@json, 2, len(@json) - 2), '"','')
print @sql
exec ('select ' + @sql + ' from dbo.Client')