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?
2条答案
按热度按时间agyaoht71#
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
Usage
wj8zmpe12#
You can just use an
IIF
orCASE
withinOPENJSON
The
CROSS APPLY
will automatically remove any row which do not have the relevant JSON property, or are null.