Can we pass parameters to a view in SQL? Can we pass parameters to a view in SQL? sql-server sql-server

Can we pass parameters to a view in SQL?


As already stated you can't.

A possible solution would be to implement a stored function, like:

CREATE FUNCTION v_emp (@pintEno INT)RETURNS TABLEASRETURN   SELECT * FROM emp WHERE emp_id=@pintEno;

This allows you to use it as a normal view, with:

SELECT * FROM v_emp(10)


There are two ways to achieve what you want. Unfortunately, neither can be done using a view.

You can either create a table valued user defined function that takes the parameter you want and returns a query result

Or you can do pretty much the same thing but create a stored procedure instead of a user defined function.

For example:

the stored procedure would look like

CREATE PROCEDURE s_emp(    @enoNumber INT) AS SELECT    * FROM    emp WHERE     emp_id=@enoNumber

Or the user defined function would look like

CREATE FUNCTION u_emp(       @enoNumber INT)RETURNS TABLE ASRETURN (    SELECT            *     FROM            emp     WHERE             emp_id=@enoNumber)


Normally views are not parameterized. But you could always inject some parameters. For example using session context:

CREATE VIEW my_viewASSELECT *FROM tabWHERE num = SESSION_CONTEXT(N'my_num');

Invocation:

EXEC sp_set_session_context 'my_num', 1; SELECT * FROM my_view;

And another:

EXEC sp_set_session_context 'my_num', 2; SELECT * FROM my_view;

DBFiddle Demo

The same is applicable for Oracle (of course syntax for context function is different).