我们能否在Microsoft SQL Server中向视图传递参数?
我尝试以以下方式创建视图,但它不起作用:
create or replace view v_emp(eno number) as select * from emp where emp_id=&eno;
我们能否在Microsoft SQL Server中向视图传递参数?
我尝试以以下方式创建视图,但它不起作用:
create or replace view v_emp(eno number) as select * from emp where emp_id=&eno;
是的,您可以使用SESSION_CONTEXT()函数或临时表。这里是使用同义词的临时表方法的完整指南:
--1. prepare your data
drop table if exists #temp_table;
select 1 as id, 'magic' as val into #temp_table; --if you change table definition (add/drop columns f.e.) you will need to recompile the view
drop synonym if exists table_synonym;
create synonym table_synonym for #temp_table;
go
--2. create a view
create or alter view some_view
as
select * from table_synonym --It is a hack and I'm not sure that it will work for your server. I test this on version 15.0.2000.5
go
--3. enjoy
select * from some_view
go
--you can delete the synonym and the temp table without breaking some_view (but you would not be able to select the data)
drop table if exists #temp_table
drop synonym if exists table_synonym;
go
select * from some_view
go
我根据自己的需求完成了这个任务,具体如下:
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