如何将JSON与表连接?

时间:2018-12-11 00:31:33

标签: sql-server

我有一个带有列名的主表,例如:

Table name: user_attribute
---------------------------------
ColumnId    ColumnName
---------------------------------
1           Name
2           Email
3           Phone

另一个带有JSON列示例的表:

Table name: user_detail
------------------------------------
UserId      UserInformation
------------------------------------
1     {"Name":"abc","Email":"abc@test.com","Phone":"23231233","Company":"test"}
2     {"Name":"xyz","Email":"xyz@test.com","Phone":"8909788","Location":"NA"}

我正在尝试编写一个动态视图,该视图可以以表格格式显示JSON信息,但只能显示那些属于主表的列。

我可以通过对JSON属性进行硬编码来使用JSON_VALUE函数来做到这一点,但我想避免这种情况。这样,无论何时我在主表“ user_attribute”中添加新值,该值都应反映在视图中。

1 个答案:

答案 0 :(得分:2)

给出如下设置:

declare @attributes table (Id int identity(1,1), Name sysname);

insert into @attributes (Name)
values
('Name'),('Email'),('Phone');

declare @data table (
  UserId int,
  JData nvarchar(max)
);

insert into @data (UserId, JData)
values
(1, N'{"Name":"abc","Email":"abc@test.com","Phone":"23231233","Company":"test"}'),
(2, N'{"Name":"xyz","Email":"xyz@test.com","Phone":"8909788","Location":"NA"}');

,从JSON blob中仅过滤必要的属性非常容易:

select d.UserId, ua.*
from @data d
  cross apply openjson(d.JData) ua
  inner join @attributes a on a.Name = ua.[key] collate database_default;

OPENJSON函数至少需要SQL Server 2016才能工作。