我想根据前缀创建一个联合特定表的视图 它是在SQL 2008服务器上运行的数据库。
表名如下:
Table_XXX_13_1 ; Table_XXX_14_2 ;Table_XXX_15_3 ; Table_XXX_15_4 ...
等
新视图名称:'View_XXX_15'
我该怎么办?
我想过滤“Table_XXX_15%
”,尝试使用选择内容,
请列出一些信息,我是SQL的新手。
链接到类似的问题:I need to create a view that unions all tables based on their prefix (new tables added monthly)
修改
以下代码不起作用:
CREATE PROCEDURE spCreateView2015
@BaseTableName varchar(100),
@View varchar(100),
@s varchar(max),
@v varchar(max)
AS
BEGIN
SET NOCOUNT ON;
set @BaseTableName = 'Table%15%';
set @View = 'View_097_001_test';
set @v =
N'(
select stuff((
select cast('' union all select * from '' as nvarchar(max)) + quotename(''CEE_097_001'')
from information_schema.tables
where table_name like @BaseTableName))
)';
set @s = 'DROP VIEW ' + @View;
EXEC (@s);
set @c = N'CREATE VIEW @View AS ' + @v;
EXEC Sp_executesql @c, N'@View varchar(100), @BaseTableName varchar(100)', @View, @BaseTableName;
输出:
过程或函数'spCreateView2015'需要参数'@BaseTableName',这是未提供的。
答案 0 :(得分:0)
Database
附近缺少引号,设置动态变量@v
时应添加引号。应该是这样的:
CREATE PROCEDURE spCreateView2015
@BaseTableName varchar(100) = 'Table_XXX_15%',
@View varchar(100) = 'View_XXX_2015'
AS
BEGIN
SET NOCOUNT ON;
declare @v nvarchar(max)
set @v =
'(
select stuff((
select cast('' union all select * from '' as nvarchar(max)) + quotename(''Database'')
from information_schema.tables
where name like @BaseTableName))
);'
declare @s nvarchar(max) = 'DROP VIEW ' + @View;
EXEC Sp_executesql @s, N'@BaseTableName varchar(100), @View varchar(100)', @BaseTableName, @View
declare @c nvarchar(max) = 'CREATE VIEW ' + @View + ' AS ' + @v;
EXEC Sp_executesql @c, N'@BaseTableName varchar(100), @View varchar(100)', @BaseTableName, @View
END