Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

Insert data from Json table to the view that has been already created in SQL

I have a problem, I have to insert data from a Json that stored in a table that has jus one field, just directly insert to the view but as I know there isn't any way to update or insert data into the view, do any one know how can I adjust or set my view to insert data from my table(PS: i can't use insert into or select into)

my first table that has Json data:

|  JsonOutPut                                                                   |
|-------------------------------------------------------------------------------|
|[{"FID":1,"Fname":"cake","Fcount":5,"FDate":"2020-02-13","Fregion":"UK"},...]  |

my view should be like this:

| FID | Fname | Fcount| FDate    | Fregion |
|-----|-------|-------|----------|---------|
|  1  | cake  |   5   |2020-02-13|    UK   |

I don't want create new table!

question from:https://stackoverflow.com/questions/65641133/insert-data-from-json-table-to-the-view-that-has-been-already-created-in-sql

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
create table jtable(JsonOutPut nvarchar(max));
go
insert into jtable(JsonOutPut)
values('[{"FID":1,"Fname":"cake","Fcount":5,"FDate":"2020-02-13","Fregion":"UK"},{"FID":2,"Fname":"pie","Fcount":15,"FDate":"2020-02-15","Fregion":"UK"}]'),
('[{"FID":100,"Fname":"cake100","Fcount":1005,"FDate":"2020-02-13","Fregion":"UK100"},{"FID":1002,"Fname":"pie100","Fcount":10015,"FDate":"2020-02-15","Fregion":"UK100"}]');
go

create view jview
as
select oj.FID, oj.Fname, oj.Fcount, oj.FDate, oj.Fregion
from jtable
cross apply openjson(JsonOutPut) 
with
(
FID int '$.FID',
Fname varchar(100) '$.Fname',
Fcount int '$.Fcount',
FDate date '$.FDate',
Fregion varchar(20) '$.Fregion'
) as oj
go

select *
from jview
go

drop view if exists jview
drop table if exists jtable
go

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...