展开查询中的所有视图查询

时间:2018-01-31 06:28:57

标签: sql sql-server tsql

我有这样的疑问:

SELECT
  *
FROM vwUsers
LEFT JOIN tblLocations
  ON vwUsers.id = tblLocations.owner

是否有自动扩展此查询以包含视图语句(以及任何嵌套视图语句)的方法?我想最终得到类似的东西:

SELECT * FROM 
    (SELECT id,name,     -- vwUsers expanded into it's defining statement
     FROM tblUsers 
     LEFT JOIN tblNames 
     ON tblUsers.id = tblNames.id) AS vwUsers
LEFT JOIN tblLocations
ON vwUsers.id = tblLocations.owner

1 个答案:

答案 0 :(得分:1)

解决方案似乎很清楚:

  1. 创建包含所有参考视图的列表
  2. 获取他们的定义
  3. 替换查询中的定义
  4. 在我的环境中有这样的事情:

    <?php
    $args = array(
      'order' => (isset($_GET['orderby']) ? $_GET['orderby'] : 'ASC')
    );
    query_posts($args);
    ?>
    
    <div class="sort_by">
      <span>Sort by:</span>
      <span class="relevance <?php if(!isset($_GET['order'])){ echo 'activesearch';} ?>"><a href="?s=<?php echo $_GET['s']; ?>">Relevance</a></span>
      <span class="newest <?php if(isset($_GET['order']) && $_GET['order']=='DESC'){ echo 'activesearch';}else{ echo '';} ?>"><a href="?s=<?php echo $_GET['s']; ?>&orderby=post_date&order=DESC" >Newest</a></span>
      <span class="oldest <?php if(isset($_GET['order']) && $_GET['order']== 'ASC'){ echo 'activesearch';}else{ echo '';} ?>"><a href="?s=<?php echo $_GET['s']; ?>&&orderby=post_date&order=ASC">Oldest</a></span>
    </div>
    

    为了实现自动化,必须处理以下情况:

    • 我们可以使用正则表达式匹配
    • 自动获取引用的对象
    • 我们可以使用regex
    • 自动替换DECLARE @Objects TABLE ( [ObjectName] SYSNAME ,[Definition] NVARCHAR(MAX) ); INSERT INTO @Objects ([ObjectName]) VALUES ('[dbo].[SurveyInstancesHistory]') ,('dbo.vw_MystClients'); UPDATE @Objects SET [Definition] = M.[definition] FROM @Objects O INNER JOIN [sys].[objects] OB ON OBJECT_ID([ObjectName]) = OB.[object_id] INNER JOIN [sys].[sql_modules] M ON OBJECT_ID([ObjectName]) = M.[object_id] WHERE OB.[type] = 'V'; DECLARE @DynamicTSQLStatement NVARCHAR(MAX) = N' SELECT * FROM SurveyInstances SI INNER JOIN [dbo].[SurveyInstancesHistory] SIH ON SI.[SurveyInstanceID] = SIH.[SurveyInstanceID] INNER JOIN ProtoSurveys PS ON SI.[ProtoSurveyID] = PS.[ProtoSurveyID] INNER JOIN dbo.vw_MystClients MC ON PS.[ClientID] = MC.[Client<br>ID];' SELECT @DynamicTSQLStatement = REPLACE(@DynamicTSQLStatement, [ObjectName], '(' + [Definition] + ') AS ' + [ObjectName]) FROM @Objects; SELECT @DynamicTSQLStatement; 语句

    在您需要一个始终在您的示例中工作的脚本时,您需要自己编写正则表达式,因为人们正在使用不同的语法创建视图。由于可以手动使用和编辑上述内容以便运行,因此可以根据您的需要创建非常复杂的脚本。

    强烈重新开始实现String Utility Functions Sample,以便在T-SQL中获得正则表达式支持。