Can we pass parameters to a view in SQL?

前端 未结 20 2370
庸人自扰
庸人自扰 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:41

    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
    

提交回复
热议问题