I have this stored procedure where I export some data from a SQL Server table to json file.
It works all fine when I only have one SQL query which makes sense because it exports only one json file.
But what I want to do is create two json files from two SQL Server tables from a single procedure...
Right now my stored procedure (working) looks like this:
ALTER PROCEDURE [dbo].[SP_PopulateJsonFiles]
AS
DECLARE @sql varchar(1000)
DECLARE @FileName varchar(500)
SET @FileName = '\\C:\Projects\JsonFiles\Sqltable1.json'
SET @sql = 'bcp "' +
'select * from Sqltable1'+
--if I add this line down it breaks the procedure and exports nothing :(
'select * from [Audit]'+
' FOR JSON PATH, INCLUDE_NULL_VALUES" ' +
'queryout "'+@FileName+ '"' +
' -c -S myMachine -d myDatabase-T'
EXEC sys.XP_CMDSHELL @sql
GO
So right now it only works if I only write 'select * from Sqltable1'+
but now if I put another select statement in it.
I get that it runs into a conflict with the name because this way will try to create two documents with the same name, but how can I escape this and create two separate files with different names maybe?
Thank you in advance.
I found a solution to this so I am posting just in case someone might need this in the future too.
ALTER PROCEDURE [dbo].[SP_PopulateJsonFiles]
AS
DECLARE @sql varchar(1000)
DECLARE @FileName varchar(500)
--for the first table and first file
SET @FileName = '\\C:\Projects\JsonFiles\Sqltable1.json'
SET @sql = 'bcp "' +
'select * from Sqltable1'+
' FOR JSON PATH, INCLUDE_NULL_VALUES" ' +
'queryout "'+@FileName+ '"' +
' -c -S myMachine -d myDatabase-T'
EXEC sys.XP_CMDSHELL @sql
--for the second table and second file
SET @FileName = '\\C:\Projects\JsonFiles\Sqltable2.json'
SET @sql = 'bcp "' +
'select * from Sqltable2'+
' FOR JSON PATH, INCLUDE_NULL_VALUES" ' +
'queryout "'+@FileName+ '"' +
' -c -S myMachine -d myDatabase-T'
EXEC sys.XP_CMDSHELL @sql
GO