我想创建存储过程,该存储过程根据输入参数有条件地输出JSON。无需重复执行select语句就可以做到吗?
CREATE PROCEDURE myProcedure @outputJson bit
AS
BEGIN
IF outputJson = 1
BEGIN
SELECT col1,
col2,
col3
FROM dbo.MyTable
FOR JSON PATH
END
ELSE
BEGIN
SELECT col1,
col2,
col3
FROM dbo.MyTable
END
END
GO
答案 0 :(得分:2)
您可以使用动态SQL在参数中包含“ FOR JSON”子句。
CREATE PROCEDURE dbo.myProcedure @outputJson bit
AS
BEGIN
DECLARE @sql nvarchar(max) = N'SELECT col1, col2, col3 FROM dbo.MyTable';
IF @outputJson = 1
BEGIN
SET @sql += ' FOR JSON PATH';
END
EXECUTE sp_executesql @sql;
END
GO