Reputation: 301
I tried the following code but I am getting a syntax error:
ORDER BY
Date ASC
IF (@Format = 'JSON')
FOR JSON AUTO
Is it possible to do this? I am trying to control whether the output of this stored procedure is a table or a JSON document via an input parameter.
Upvotes: 2
Views: 113
Reputation: 12395
To dynamically alter your query you can use dynamic TSQL:
create table #tmp ([Date] datetime2)
insert into #tmp values
('2018-04-01')
,('2018-04-11')
,('2018-03-21')
,('2018-06-01')
,('2018-07-01')
declare @Format varchar(50)= 'JSON'
declare @sql nvarchar(max)= ''
set @sql += ' select * from #tmp '
set @sql += ' ORDER BY '
set @sql += ' Date ASC'
if (@Format = 'JSON')
set @sql += ' FOR JSON AUTO'
exec (@sql)
Result:
Now if you execute again the code changing the value of @Format
variable:
declare @Format varchar(50)= 'other'
Result:
Another solution is to call different stored procedures depending on the value of your variable:
if (@Format = 'JSON')
exec dbo.My_SP_that_Returns_JSON
else
exec dbo.My_SP_that_Returns_a_table
Upvotes: 1