-1

I have a query where the result changes according to the parameter. I have created a stored procedure to show what I need. I want it in a view so that I can join with other tables.

CREATE PROCEDURE [SP_getTableByInputParameter]
    @inputParam INT
AS
BEGIN 
    IF (@inputParam = 1)
    BEGIN 
        SELECT
            cp.CompanyId, x.value AS Leavetypeid 
        FROM
            CompProperty CP 
        CROSS APPLY
            OPENJSON(cp.Properties, '$.Manageid') AS x
        WHERE
            CP.Properties IS NOT NULL 
            AND CP.CategoryId = 2 
            AND CP.Priority = 1 
            AND CP.Properties LIKE '%Manageid%'
    END
    ELSE IF (@inputParam = 2)
    BEGIN 
        SELECT 
            cp.CompanyId, x.value AS Leavetypeid 
        FROM
            CompProperty CP 
        CROSS APPLY
            OPENJSON(cp.Properties, '$.Unmanageid') AS x
        WHERE
            CP.Properties IS NOT NULL 
            AND CP.CategoryId = 2 
            AND CP.Priority = 1 
            AND CP.Properties LIKE '%UnManageid%'
    END
END

The view I need is something like

SELECT *
FROM company c
INNER JOIN SP_getTableByInputParameter(l) J ON c.companyid = J.companyid

I tried to create view as same as the procedure. But it didn't work.

Any idea?

4

2 Answers 2

0

Just to expand on my comment AND offer a little twist ... Note the CHOOSE() function.

The dynamic JSON attribute will fail in 2016 but works in 2017+

Example

CREATE FUNCTION [dbo].[tvf_getTableByInputParameter]( @inputParam INT )

Returns Table 
As
Return (  

select cp.CompanyId
      ,x.value as Leavetypeid 
 from CompProperty CP 
 cross apply openjson(cp.Properties,choose(@inputParm,'$.Manageid','$.Unmanageid')) as x
 where  CP.Properties IS NOT NULL 
   and CP.CategoryId = 2 
   and CP.Priority = 1 
   and CP.Properties like choose(@inputParm,'%Manageid%','%UnManageid%')
)

Usage

Select *
 From [dbo].[tvf_getTableByInputParameter](1)
Sign up to request clarification or add additional context in comments.

Comments

0

You can just use an IIF or CASE within OPENJSON

CREATE PROCEDURE [SP_getTableByInputParameter]
    @inputParam INT
AS

SELECT
  cp.CompanyId,
  x.value AS Leavetypeid 
FROM
    CompProperty CP 
CROSS APPLY
    OPENJSON(CP.Properties, IIF(@inputParam = 1, '$.Manageid', '$.Unmanageid')) AS x
WHERE CP.CategoryId = 2 
  AND CP.Priority = 1;

The CROSS APPLY will automatically remove any row which do not have the relevant JSON property, or are null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.