在存储过程中创建VIEW的问题

时间:2019-04-24 21:27:28

标签: sql-server

我需要从SQL Server 2008 R2表中的列中解析JSON字符串,因此我使用了2个视图和3个表以及几个分步查询。一切正常。

现在,在填充几个数据库之后,我需要允许将触发器放置在特定的表上。由于只能从触发器调用存储过程,因此我将所有内容都转换为存储过程。

CREATE VIEW语句外,其他所有程序都运行良好。我已经将其包装到EXEC中,但是对于未封闭的引号,我仍然遇到语法错误。我尝试了几种不同的关键字括起来方法,但是没有任何效果。

以下是代码段:

EXEC ('If object_ID(''vw_BuildLookup01'',''V'') IS NOT NULL
            DROP VIEW vw_BuildLookup01;')
EXEC ('If object_ID(''vw_BuildLookup02'',''V'') IS NOT NULL
            DROP VIEW vw_BuildLookup02;')

EXEC ('CREATE VIEW [dbo].[vw_BuildLookup01]
  AS
  SELECT DISTINCT t.tblKey, t.Name AS MetricTypesName, m.tblKey AS MetricKey, m.Name AS MetricName, 
  m.MetricLimitedValues, f.Value
  FROM  OccurrenceMetricFacts f
  INNER JOIN Metrics m ON f.MetricKey = m.tblKey 
  INNER JOIN MetricTypes t ON m.MetricTypeKey = t.tblKey 
  WHERE  m.MetricLimitedValues IS NOT NULL AND t.DeletedDate IS NULL AND f.Value IS NOT NULL
')

EXEC ('CREATE VIEW [dbo].[vw_BuildLookup02]
  AS
  SELECT v.tblKey, v.MetricTypesName, v.MetricKey, v.MetricName,
  REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(v.MetricLimitedValues, '"Name":"', ''),'","Value"', ''),'{', ''), '}',''),'[', ''), ']', '') AS MetricLimitedValues, v.Value
  FROM vw_BuildLookup01 v
  INNER JOIN MetricTypes t ON t.tblKey = v.tblKey
  WHERE t.DeletedDate IS NULL
')

语法错误在线:

CREATE VIEW [dbo].[vw_BuildLookup02] 

在嵌套的REPLACE命令之后,““ Name”:“'在其下面有可怕的红色波浪线。

1 个答案:

答案 0 :(得分:0)

以下是我对PUBS数据库所做的示例。

由于它正在执行EXEC,因此整个sql都以一个开/关单引号引起来。

所有内部引号必须是一对单引号。

EXEC ('CREATE VIEW [dbo].[vw_BuildLookup02]
AS
SELECT
        [title_id]
       ,[title]
       ,REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        v.title, ''Name'', ''''),
         ''Value'', ''''),
         ''{'', ''''),
         ''}'', ''''),
         ''['', ''''),
         '']'', '''') 

        AS title2 

    FROM [pubs].[dbo].[titles] as v
    ');