For Auto JSON with where condition

RajKumar 101 Reputation points
2022-08-08T15:33:05.703+00:00

Hi All,

I need to create a view to export the data in SON format and i need to limit the data by adding where condition. Please see the view and sample select statements.

Create view abc
as
select emp,ename,sal from emp for auto json

running t-sql queries

Select * from abc where emp=1
or
Select * from abc where ename='abc'

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,625 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jingyang Li 5,891 Reputation points
    2022-08-10T03:18:02.727+00:00

    Are you going through the hard way to filter your view?
    Try these sample (it is possible but not efficient)
    Drop table if exists emp;
    create table emp (emp int,ename varchar(10),sal decimal(6,2))
    insert into emp values(1,'name1',1000),(2,'abc',2000),(3,'def',3000)

    go  
    Drop view  if  exists abc;  
    go  
    Create view abc  
    (jsonCol)  
    as  
    select emp,ename,sal   
    from emp for json auto  
      
    go  
    --example 1  
    ;with mycte as (  
    SELECT *   
    FROM OPENJSON(CONVERT(NVARCHAR(MAX),(select jsonCol from abc)))  
    WITH  
        (  
    	emp int,  
        ename VARCHAR(200) '$.ename',  
        sal decimal(6,2) '$.sal'  
        )  
    	 WHERE emp = '1' )  
      
     Select * from mycte  for json auto  
      
    --example 2  
    ;with mycte2 as (  
    SELECT *   
    FROM OPENJSON(CONVERT(NVARCHAR(MAX),(select * from abc)))  
       WITH  
        (  
    	emp int,  
        ename VARCHAR(200) '$.ename',  
        sal decimal(6,2) '$.sal'  
        )  
        WHERE ename = 'abc'  
    	)  
      
     Select * from mycte2  for json auto  
    
    0 comments No comments

6 additional answers

Sort by: Most helpful
  1. Jingyang Li 5,891 Reputation points
    2022-08-08T17:44:16.697+00:00

    you cannot pass parameter to a view in SQL Server. You can use a stored procedure to pass parameter instead.

    0 comments No comments

  2. RajKumar 101 Reputation points
    2022-08-08T18:40:26.763+00:00

    I am not passing any parameters. I am only running the select statement by a where condition.

    0 comments No comments

  3. Jingyang Li 1 Reputation point
    2022-08-08T19:21:29.217+00:00

    Create view abc
    as
    select emp,ename,sal from emp
    where emp=1
    for json auto

    0 comments No comments

  4. RajKumar 101 Reputation points
    2022-08-08T19:42:06.993+00:00

    I do not want to alter the View for each where condition.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.