I'm trying to write a query in SQL Server 2016 where I:
- loop through a series of rows
- read the results into variables
- create JSON objects from those variables to store in my database
This is a basic example of the code I have so far
DECLARE
@test1 int,
@test2 varchar(255)
DECLARE db_update_cursor CURSOR FOR
SELECT test1, test2
FROM sourceTable
OPEN db_update_cursor
FETCH NEXT FROM db_update_cursor INTO @test1, @test2
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO destinationTable(testRow)
VALUES (SELECT @test1, @test2 FOR JSON AUTO)
FETCH NEXT FROM db_update_cursor INTO @test1, @test2
END
CLOSE db_update_cursor
DEALLOCATE db_update_cursor
From this, I am hoping to get a Json object that looks something like this:
[
{
"test1": 5,
"test2": "something"
}
]
When I try to run this, I am getting the error: "FOR JSON AUTO requires at least one table for generating JSON objects. Use FOR JSON PATH or add a FROM clause with a table name."
What is the best way to implement this workflow?