Can we pass parameters to a view in SQL?

前端 未结 20 2118
庸人自扰
庸人自扰 2020-11-29 18:29

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         


        
相关标签:
20条回答
  • 2020-11-29 18:49

    No, a view is queried no differently to SELECTing from a table.

    To do what you want, use a table-valued user-defined function with one or more parameters

    0 讨论(0)
  • 2020-11-29 18:50

    A view is nothing more than a predifined 'SELECT' statement. So the only real answer would be: No, you cannot.

    I think what you really want to do is create a stored procedure, where in principle you can use any valid SQL to do whatever you want, including accept parameters and select data.

    It seems likely that you really only need to add a where clause when you select from your view though, but you didn't really provide enough details to be sure.

    0 讨论(0)
  • 2020-11-29 18:51

    Your view can reference some external table containing your parameters.

    As others mentioned, the view in SQL Server cannot have external input parameters. However, you can easily fake a variable in your view using CTE. You can test-run it in your version of SQL Server.

    CREATE VIEW vwImportant_Users AS
    WITH params AS (
        SELECT 
        varType='%Admin%', 
        varMinStatus=1)
    SELECT status, name 
        FROM sys.sysusers, params
        WHERE status > varMinStatus OR name LIKE varType
    
    SELECT * FROM vwImportant_Users
    

    yielding output:

    status  name
    12      dbo
    0       db_accessadmin
    0       db_securityadmin
    0       db_ddladmin
    

    also via JOIN

    WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
    SELECT status, name 
        FROM sys.sysusers INNER JOIN params ON 1=1
        WHERE status > varMinStatus OR name LIKE varType
    

    also via CROSS APPLY

    WITH params AS ( SELECT varType='%Admin%', varMinStatus=1)
    SELECT status, name 
        FROM sys.sysusers CROSS APPLY params
        WHERE status > varMinStatus OR name LIKE varType
    
    0 讨论(0)
  • 2020-11-29 18:57

    As already stated you can't.

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

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

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

    SELECT * FROM v_emp(10)
    
    0 讨论(0)
  • 2020-11-29 18:57

    You can bypass just to run the view, SQL will wine and cry but just do this and run it! You can't save.

    create or replace view v_emp(eno number) as select * from emp where (emp_id = @Parameter1);
    
    0 讨论(0)
  • 2020-11-29 18:58

    Why do you need a parameter in view? You might just use WHERE clause.

    create view v_emp as select * from emp ;
    

    and your query should do the job:

    select * from v_emp where emp_id=&eno;
    
    0 讨论(0)
提交回复
热议问题