如何在OPENJSON查询的WITH子句中给出动态列名?

问题描述 投票:2回答:1

我有不同的json格式,并希望使用OPENJSON.Table名称在不同的表中插入不同的格式能够动态给出。但是如何动态给出列?我的查询如下:

DECLARE @jsonVariable NVARCHAR(MAX)
DECLARE @TableName NVARCHAR(MAX)

SET @jsonVariable =  
    N'{ "id" : "12","info": { "fname": "John", "surname": "Smith" },"table":"Students" }'  

SET @TableName = (SELECT JSON_VALUE(@jsonVariable , '$.table'))

DECLARE @SQL AS VARCHAR(MAX) = '
 INSERT INTO ' + @TableName + '
 SELECT *  
 FROM OPENJSON(' + '''' + @jsonVariable + '''' + ')  
 WITH (id int,fname nvarchar(50) ''$.info.fname'') '

EXEC(@SQL)

在Students表中,只有2列:id和fname.So在WITH子句中传递id和fname。说我有另一个json:

SET @jsonVariable =  N'{ "id" : "12","fname": "John", "lname": "Smith", "age": 25, "table":"Employees" }'  

在Employees表中,有4列:id,fname,lname,age。并希望将第二个json数据放在Employees表中。那么如何动态更改WITH子句还是有其他解决方案?

sql sql-server
1个回答
1
投票

这是一个解析JSON并将其插入表中的存储过程:

create or alter procedure dbo.InsertJson(@json nvarchar(max))
as begin
    declare @id int = json_value(@json, '$.id')
    declare @info nvarchar(max) = json_query(@json, '$.info')
    declare @table sysname = json_value(@json, '$.table')

    declare @columns nvarchar(max) = ''
    declare @values nvarchar(max) = ''
    select  @columns = @columns + case when @columns = '' then '' else ', ' end + 
                quotename([key])
    ,       @values = @values + case when @values = '' then '''' else ', ''' end + 
                replace([value], '''', '''''') + ''''
    from    openjson(@info);

    declare @sql nvarchar(max) = 
        'insert ' + quotename(@table) + 
        '       (id, ' + @columns + ') ' +
        'values (' + cast(@id as varchar) + ', ' + @values + ')';
    exec(@sql)
end

用法示例:

create table t1 (id int, col1 int);
create table t2 (id int, col1 int, col2 int);
exec dbo.InsertJson '{ "id" : "1", "info": { "col1": "1"}, "table":"t1" }';
exec dbo.InsertJson '{ "id" : "1", "info": { "col1": "1", "col2": "2"}, "table":"t2" }';
select * from t1;
select * from t2;
© www.soinside.com 2019 - 2024. All rights reserved.