【问题标题】:Creating view that unions specific tables based on prefix创建基于前缀联合特定表的视图
【发布时间】:2015-03-31 10:15:33
【问题描述】:

我想创建一个视图,根据前缀合并特定表。
它是在 SQL 2008 服务器上运行的数据库。

表命名如下:
Table_XXX_13_1 ; Table_XXX_14_2 ;Table_XXX_15_3 ; Table_XXX_15_4 ...

新视图名称:“View_XXX_15”

我应该如何进行? 我想过滤“Table_XXX_15%”,尝试使用 Select stuff
请列出一些信息,我是 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”,但未提供。

【问题讨论】:

  • 您已经找到了解决方案。什么不起作用?
  • 见上文,刚刚编辑过。
  • 什么不起作用?
  • 发布您用来调用存储过程的代码。你没有正确调用它。

标签: sql sql-server sql-server-2008 view union


【解决方案1】:

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

【讨论】:

  • 运行脚本后出现错误。见输出。
  • 您需要执行以下动态变量:EXEC Sp_executesql @s, N'@BaseTableName varchar(100), @View varchar(100)', @BaseTableName, @View
猜你喜欢
  • 2011-09-09
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 2011-11-08
  • 2021-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多