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 o
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
and Customer
so you get a new "table" of rows from Order
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 the Order
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").
no you can pass the parameter to the procedure in view
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.
There are 2 ways to acheive what you want unfortunatly 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
AS
RETURN
(
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_view
AS
SELECT *
FROM tab
WHERE 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).
I realized this task for my needs as follows
set nocount on;
declare @ToDate date = dateadd(month,datediff(month,0,getdate())-1,0)
declare @year varchar(4) = year(@ToDate)
declare @month varchar(2) = month(@ToDate)
declare @sql nvarchar(max)
set @sql = N'
create or alter view dbo.wTempLogs
as
select * from dbo.y2019
where
year(LogDate) = ''_year_''
and
month(LogDate) = ''_month_'' '
select @sql = replace(replace(@sql,'_year_',@year),'_month_',@month)
execute sp_executesql @sql
declare @errmsg nvarchar(max)
set @errMsg = @sql
raiserror (@errMsg, 0,1) with nowait