代码之家  ›  专栏  ›  技术社区  ›  Eray Balkanli

如何通过在SQL Server中使用值来查找要用于from语句的相关表/视图名称

  •  0
  • Eray Balkanli  · 技术社区  · 5 年前

    我在SQL Server中有一个表X,其中包含一个名为 Type varchar(10) 有15个潜在值: AAA, BBB1, BBB2, CCC, ... ,以及另一个名为 IfExists bit .

    在同一个数据库中,我有15个不同的视图,每个视图一个 Type 包括…在内 X_ID 也视图名称示例:

    View_ReportingAAA
    View_ReportingBBB1
    View_ReportingBBB2
    View_ReportingCCC
    ....
    

    通常我所做的就是看电视 类型 通过使用 X_ID 提供给我的 Table X 并使用select查询相关视图以获取一些数据。

    我现在需要做的是为 表十 将的值设置为1 IfExists 字段,如果相关视图中有记录id的记录 X_ID .

    我的问题是: 通过使用主表中某个字段的值,找到并使用相关视图名称的最佳方法是什么?

    我正在使用下面的代码,但我不确定这是否是最有效的处理方法。任何帮助或建议都将不胜感激。

    declare @ifExists int = 0;
    declare @sql nvarchar(max) = 'set @ifExists = (Select count(*) from View_Reporting';
    
    declare @tablename nvarchar(max) = (Select Type from X where X_ID = @X_ID)
    
    set @sql = @sql + @tablename + ' where V_xid = @X_ID)';
    EXECUTE sp_executesql @sql
    
    if (@ifExists > 0)
    begin
       update X set IfExists = 1 where X_ID = @X_ID
    end
    
    1 回复  |  直到 5 年前
        1
  •  1
  •   Xabi    5 年前

    也许这更容易:

    declare @ifExists bit
    select @ifExists=count(*) from INFORMATION_SCHEMA.VIEWS
        where TABLE_NAME='View_Reporting'+(select [Type] from X where X_ID=@X_ID)
    update X set IfExists=@IfExists where X_ID=@X_ID and IfExists<>@IfExists