是否可以使用sp_executesql获取JSON作为输出参数
我正在编写一个存储过程来尝试跟踪对不同表中对象的更改 我正在尝试动态构造SQL,因此不得不使用是否可以使用sp_executesql获取JSON作为输出参数,sql,sql-server,json,tsql,stored-procedures,Sql,Sql Server,Json,Tsql,Stored Procedures,我正在编写一个存储过程来尝试跟踪对不同表中对象的更改 我正在尝试动态构造SQL,因此不得不使用sp\u executesql 到目前为止,我已经: SET @SQLInserted = 'Select * from ' + '[Diary.Day]' + ' Where Id=' + '13'+ ' for json path'; SET @SQLClash = 'Select * from ' + '[Diary.Day]' + ' Where Id=' + '12'+ ' for jso
sp\u executesql
到目前为止,我已经:
SET @SQLInserted = 'Select * from ' + '[Diary.Day]' + ' Where Id=' + '13'+ ' for json path';
SET @SQLClash = 'Select * from ' + '[Diary.Day]' + ' Where Id=' + '12'+ ' for json path';
DECLARE @jsonInserted NVARCHAR(MAX), @jsonClash NVARCHAR(MAX)
DECLARE @SQLInserted nvarchar(500), @SQLClash nvarchar(500);
SET @SQLInserted = 'Select * from ' + '[Diary.Day]' + ' Where Id=' + '13'+ ' for json path';
SET @SQLClash = 'Select * from ' + '[Diary.Day]' + ' Where Id=' + '12'+ ' for json path';
exec sp_executesql @SQLInserted
exec sp_executesql @SQLClash
Insert Into [Log.Transaction] ([Table], [EntryTimeRaw], [OldObject], [NewObject], [Operation])
Values ('[Diary.Day]', 10000000, @jsonInserted, @jsonClash, 'CLASH')
其中,[Diary.Day]
和[Id]
是传递到存储过程中的参数
然后,我可以使用sp_executesql
运行此sql并显示JSON对象
但我不希望将该对象放入变量中,以便能够将其插入表中
到目前为止,我已经:
SET @SQLInserted = 'Select * from ' + '[Diary.Day]' + ' Where Id=' + '13'+ ' for json path';
SET @SQLClash = 'Select * from ' + '[Diary.Day]' + ' Where Id=' + '12'+ ' for json path';
DECLARE @jsonInserted NVARCHAR(MAX), @jsonClash NVARCHAR(MAX)
DECLARE @SQLInserted nvarchar(500), @SQLClash nvarchar(500);
SET @SQLInserted = 'Select * from ' + '[Diary.Day]' + ' Where Id=' + '13'+ ' for json path';
SET @SQLClash = 'Select * from ' + '[Diary.Day]' + ' Where Id=' + '12'+ ' for json path';
exec sp_executesql @SQLInserted
exec sp_executesql @SQLClash
Insert Into [Log.Transaction] ([Table], [EntryTimeRaw], [OldObject], [NewObject], [Operation])
Values ('[Diary.Day]', 10000000, @jsonInserted, @jsonClash, 'CLASH')
但是显然,@jsonInserted
和@jsonClash
变量没有被赋值,因此上面的SQL不会插入任何内容
在使用
sp_executesql
时,是否可以将JSON指定为输出参数,或者我是否做错了什么?我没有测试这个示例,因为我有SQL 2014。
结果应该是这样
DECLARE @jsonInserted NVARCHAR(MAX), @jsonClash NVARCHAR(MAX)
DECLARE @SQL NVARCHAR(500)
SET @SQL = N'SET @json = (SELECT * FROM [Diary.Day] WHERE Id = @Id FOR JSON PATH)';
EXEC sp_executesql @SQL, N'@id INT, @json NVARCHAR(MAX) OUTPUT', @id = 12, @json = @jsonInserted OUTPUT
EXEC sp_executesql @SQL, N'@id INT, @json NVARCHAR(MAX) OUTPUT', @id = 13, @json = @jsonClash OUTPUT
INSERT INTO [Log.Transaction] ([Table], [EntryTimeRaw], [OldObject], [NewObject], [Operation]) VALUES ('[Diary.Day]', 10000000, @jsonInserted, @jsonClash, 'CLASH')
这正是我最终要做的。我自己算出来的,正要发回,然后看到了你的答案。伟大的解决方案!