Creating a SQL View with parameters

46,575

Solution 1

I don't think so you can create a parameter in a View .But you can create a function which takes input parameter like the one below .

CREATE FUNCTION dbo.Sample (@Parameter varchar(10))
RETURNS TABLE
AS
RETURN
(
 SELECT Field1, Field2,....
 FROM YourTable
 WHERE Field3 = @Parameter
)

Solution 2

No, from MSDN

Creates a virtual table whose contents (columns and rows) are defined by a query. Use this statement to create a view of the data in one or more tables in the database. For example, a view can be used for the following purposes:

To focus, simplify, and customize the perception each user has of the database.

As a security mechanism by allowing users to access data through the view, without granting the users permissions to directly access the underlying base tables.

To provide a backward compatible interface to emulate a table whose schema has changed.

So, basically, this acts just like a table, and the only way that you can add "parameters" to a table is via filter statements when accessing the view

Share:
46,575
xorpower
Author by

xorpower

Reached 500 Repo on May 22'11 Reached 600 Repo on Jul 29'11 Reached 700 Repo on Aug 10'11 Reached 800 Repo on Sep 09'11 Reached 900 Repo on Oct 13'11 Reached (& crossed) 1000 Repo during Mar 14-19'12 Reached 1300 Repo on May 8 2013

Updated on March 06, 2020

Comments

  • xorpower
    xorpower about 4 years

    I have a SQL Query that accepts parameters. Now When I'm trying to include that query into a view, I'm facing an error because a view cannot hold a parameters just like an SP or a function can.

    Hence if I had to create the view that had to contain the parameters, Is there someway that it is possible?

    Many Thanks

  • Suncat2000
    Suncat2000 over 7 years
    That is the most rational explanation I've heard for prohibiting parameterized views. Still stinks, though, when you need parameters to filter subqueries.
  • Suncat2000
    Suncat2000 over 7 years
    While you were being condescending, you missed the fact that you created a stored procedure, not a view.
  • user2864740
    user2864740 about 7 years
    An ITVF (as opposed to a TVF/SF) is effectively a view in terms of how it is merged into the final query.
  • vaitrafra
    vaitrafra almost 7 years
    well thanks. I searched for parametrized view and the smarta** says "you stooped, use this" and writes a stored procedures.