我正在尝试选择 JSON 属性作为列。需要选择的属性存储在其他一些表中
CREATE TABLE [Templates](
[ID] [int] NOT NULL,
[Template] [nvarchar](max)
)
INSERT INTO Templates(ID,Template)
VALUES
(1,'{"FirstName":"foo"}'),
(2,'{"FirstName":"joe","LastName":"dow"}'),
(3,'{"LastName":"smith","Address":"1234 Test Drive"}'),
(4,NULL)
Declare @SQL NVARCHAR(max)
--For brevity purpose i am hardcoding these property names. In reality column names will come from another table
DECLARE @properties NVARCHAR(max) = '[Address],[FirstName],[LastName]'
Set @SQL = '
Select '+ @properties +'
From (
Select T.ID
,j.[Key]
,j.[Value]
From Templates T
Cross Apply OpenJSON(T.Template) AS j
) src
Pivot ( max(value) for [Key] in ('+ @properties +') ) pvt
'
Exec(@SQL)
上面的代码大部分都在工作,除了最后一行Template
是 NULL。(ID = 4)
预期:查询应返回 4 行,对于最后一行,除 ID 外,所有列都应为空。