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

时间:2018-03-30 11:07:42

标签: sql sql-server

我有不同的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子句还是有其他解决方案?

1 个答案:

答案 0 :(得分:2)

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

library(dplyr)

df1 <- data.frame(Amount= c(201.1, 292.2, 218.2, 292.1), Age=c(17,19,12,19))
df2 <- df1 %>% group_by(Age) %>% summarise(Amount=mean(Amount))
df2$amount2 <- df2$Amount /200

ggplot(data=df1, aes(x=Age)) +geom_density()+
  geom_point(data=df2, aes(x=Age, y=amount2))

使用示例:

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