Can we pass a parameter to a view in Microsoft SQL Server?
I tried to create view
in the following way, but it doesn't work:
create or replace view v_emp(eno number) as select * from emp where emp_id=&eno;
Can we pass a parameter to a view in Microsoft SQL Server?
I tried to create view
in the following way, but it doesn't work:
create or replace view v_emp(eno number) as select * from emp where emp_id=&eno;
Why do you need a parameter in view? You might just use
WHERE
clause.and your query should do the job:
No you can't, as Mladen Prajdic said. Think of a view as a "static filter" on a table or a combination of tables. For example: a view may combine tables
Order
andCustomer
so you get a new "table" of rows fromOrder
along with new columns containing the customer's name and the customer number (combination of tables). Or you might create a view that selects only unprocessed orders from theOrder
table (static filter).You'd then select from the view like you would select from any other "normal" table - all "non-static" filtering must be done outside the view (like "Get all the orders for customers called Miller" or "Get unprocessed orders that came in on Dec 24th").
I have an idea that I haven't tried yet. You can do:
Your parameters will be saved and changed in the Config table.
Normally views are not paramterized. But you could always inject some parameters. For example using session context:
Invocation:
And another:
DBFiddle Demo
The same is applicable for Oracle (of course syntax for context function is different).
For downvoter: If you think that this answer is somehow incorrect, please leave a comment so I could improve it.
The point of this answer is to show that is is possible to parametrize view, but probably I wouldn't use it live (potential problems with performance and so on)
No, a view is static. One thing you can do (depending on the version of SQl server) is index a view.
In your example (querying only one table), an indexed view has no benefit to simply querying the table with an index on it, but if you are doing a lot of joins on tables with join conditions, an indexed view can greatly improve performance.
A hacky way to do it without stored procedures or functions would be to create a settings table in your database, with columns Id, Param1, Param2, etc. Insert a row into that table containing the values Id=1,Param1=0,Param2=0, etc. Then you can add a join to that table in your view to create the desired effect, and update the settings table before running the view. If you have multiple users updating the settings table and running the view concurrently things could go wrong, but otherwise it should work OK. Something like: