Skip to content

Commit 90a2b91

Browse files
committed
Adicionado script para carregar posts do Wordpress
1 parent d8a4726 commit 90a2b91

1 file changed

Lines changed: 79 additions & 0 deletions

File tree

Misc/LoadWordpressPosts.sql

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*#info
2+
# author
3+
Rodrigo Ribeiro Gomes
4+
5+
# Descricao
6+
Script de exemplo usando a nova procedure sp_invoke_external_rest_endpoint para consumir a API do Wordpress
7+
e popular uma tabela com os posts ou outros dados que possam ser retornados pela API do wordpress.
8+
9+
Funciona somente no SQL 2025 em diante.
10+
*/
11+
12+
DECLARE
13+
@PageNum int = 1
14+
,@url nvarchar(1000)
15+
,@response nvarchar(max)
16+
,@ResultCode int
17+
,@BaseUrl nvarchar(1000) = 'https://thesqltimes.com/blog'
18+
,@PerPage int = 100
19+
,@MaxPages int = 200
20+
21+
drop table if exists #posts;
22+
create table #posts (
23+
PostId int
24+
,PostJson json
25+
,PostTitle nvarchar(1000)
26+
,PostExcerpt varchar(1000)
27+
,PostUrl nvarchar(1000)
28+
,PostContent nvarchar(max)
29+
30+
)
31+
32+
33+
34+
WHILE @PageNum <= @MaxPages --> Safe!
35+
BEGIN
36+
set @url = FORMATMESSAGE('%s/wp-json/wp/v2/posts?_fields=id,title,excerpt,tags,link,content&per_page=%d&page=%d'
37+
,@BaseUrl
38+
,@PerPage
39+
,@PageNum
40+
)
41+
42+
-- get content output!
43+
RAISERROR('Loading posts from page %d',0,1,@PageNum) with nowait;
44+
declare @PostsJson nvarchar(max)
45+
exec sp_invoke_external_rest_endpoint @url
46+
,@response = @response output
47+
,@method = 'GET'
48+
49+
50+
51+
set @ResultCode = JSON_VALUE(@response,'$.response.status.http.code');
52+
RAISERROR(' Result code: %d',0,1,@ResultCode) with nowait;
53+
54+
IF @ResultCode != 200
55+
BREAK;
56+
57+
SET @PageNum += 1;
58+
59+
insert into #posts (PostId,PostTitle,PostExcerpt,PostUrl,PostContent,PostJson)
60+
select
61+
p.*
62+
from
63+
openjson(@response,'$.result') with (
64+
id int
65+
,titulo nvarchar(1000) '$.title.rendered'
66+
,resumo nvarchar(1000) '$.excerpt.rendered'
67+
,link varchar(500)
68+
,content nvarchar(max) '$.content.rendered'
69+
,RawPost nvarchar(max) '$' AS JSON
70+
) p
71+
END
72+
73+
IF @PageNum > @MaxPages
74+
BEGIN
75+
print 'Limite de páginas atingido. Verifique se a API tem mais páginas ou se houve algum problema.';
76+
RETURN;
77+
END
78+
79+
select top 3 * from #posts;

0 commit comments

Comments
 (0)