-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopenrowset_clob_demo
68 lines (62 loc) · 2.41 KB
/
openrowset_clob_demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
select openrowset_clob(
'Driver={ODBC Driver 17 for SQL Server};Server=.\TGRID4ALL;Database=ReportServer;Trusted_Connection=yes',
'WITH JSON_P AS (SELECT fruit FROM OPENJSON(cast(? as varchar(max))) WITH (fruit varchar(max)) AS JP), J(json_clob) AS (SELECT * FROM sys.databases as d1 JOIN JSON_P as jp ON (d1.name = jp.fruit) FOR JSON PATH) SELECT CAST(J.json_clob as varchar(max)) FROM J',
'[{"fruit": "tgrid4all"}, {"fruit":"WideWorldImporters"}]'
);
-- this is the CTE that we wrap around the bind parameter
WITH JSON_P AS (
SELECT fruit -- xref https://stackoverflow.com/a/31874636/40387
FROM OPENJSON(cast(? as varchar(max))) -- critical to CAST the placeholder to varchar(max)
WITH (
-- we can provide the schema inline
fruit varchar(max)
) AS JP
),
J(json_clob) AS (
SELECT *
FROM sys.databases as d1
JOIN JSON_P as jp ON (d1.name = jp.fruit) FOR JSON PATH -- this casts the result-set to JSON array of objects
) -- and coerce that to a varchar(max) so we read the entire thing as one scalar
-- without the coerce, the JSON is interpreted as a string and gets truncated
SELECT CAST(J.json_clob as varchar(max))
FROM J
declare @the_param varchar(max) = ?;
WITH JSON_P AS (
SELECT fruit
FROM OPENJSON(cast(@the_param as varchar(max))) WITH (fruit varchar(max)) AS JP
),
COLOR(color) AS (
select color
FROM OPENJSON(@the_param) WITH (color varchar(max)) as JC
),
J(json_clob) AS (
SELECT *
FROM sys.databases as d1
JOIN JSON_P as jp ON (d1.name = jp.fruit)
JOIN COLOR ON (COLOR.color = '' green '') FOR JSON PATH
)
SELECT CAST(J.json_clob as varchar(max))
FROM J
select openrowset_clob(
'Driver={ODBC Driver 17 for SQL Server};Server=.\TGRID4ALL;Database=ReportServer;Trusted_Connection=yes',
'
declare @the_param varchar(max) = ?;
WITH JSON_P AS (
SELECT [database]
FROM OPENJSON(cast(@the_param as varchar(max))) WITH ([database] varchar(max)) AS JP
),
COLOR(color) AS (
select color
FROM OPENJSON(@the_param) WITH (color varchar(max)) as JC
),
J(json_clob) AS (
SELECT d1.*
FROM sys.databases as d1
JOIN JSON_P as jp ON (d1.name = jp.[database])
JOIN COLOR ON (COLOR.color = ''green'')
FOR JSON PATH
)
SELECT CAST(J.json_clob as varchar(max))
FROM J',
'[{"database": "tgrid4all", "color" : "green"}, {"database":"WideWorldImporters", "color" : "red"}]'
);