I need to use the functionality of OPENJSON() in an old database with compatibility level 100. The server runs SQL SERVER 2016. So i came up with this idea: Create another DB "GeneralUTILS" (lvl 130) in the same server and call this function from lvl 100 DB:
CREATE FUNCTION [dbo].[OPENJSON_](@json NVARCHAR(MAX))
RETURNS @Results TABLE ([Key] nVARCHAR (4000) , [Value] NVARCHAR(MAX), [Type] INT)
AS
BEGIN
INSERT INTO @Results
SELECT * from OPENJSON(@json)
RETURN
END
But i don't have the WITH clause to modify the output table in the lvl 100 database.
Most important might be the question why you need this at all...
I hope I got correctly, what you need:
(Hint: This needs at least SQL-Server 2016)
--create two mock-up-databases
--Now we will create a stored procedure in the "higher" database
--Now we go into the "lower" database
--This is how to use it
--Clean-up (carefull with real-data!)
The most important concepts:
We cannot use the JSON-statements directly within the database, but we can create a statement on string base, pass it to the stored procedure and use
EXEC()for its execution.Using
SELECT * INTO SomeDb.SomeSchema.SomeTargetTable FROM ...will create a table with the fitting structure. Make sure to use a table not existing in your database.It is not really needed to pass the target table as parameter, you might place this in the statement yourself. Replacing the
FROMin the stored procedure is a very shrewed way and could lead into troubles iffromis found in another place.You might use similar procedures for various needs...