也许是不可能的观点 - 如此复杂

时间:2014-11-11 10:54:03

标签: sql sql-server view

我尝试实现一个视图,但我的知识还不够。

这是我的查询,我尝试制作视图

DECLARE @CTE Table(DocumentID varchar(50),DocumentNo varchar(50),XMLContent xml);
DECLARE @TBL table(DocumentID varchar(100),DocumentNo varchar(100),VData varchar(100),Vpublika varchar(100),VVatreshen varchar(100));

INSERT INTO @CTE 
SELECT DocumentID,DocumentNo,CAST(REPLACE(CAST(content AS NVARCHAR(MAX)),'utf-8','utf-16') AS XML) AS XMLContent 
FROM MainSQLTable   
WHERE DOCTYPEID = 2;

INSERT INTO @TBL 
SELECT DocumentID,DocumentNo, 
REPLACE( REPLACE (CONVERT(varchar(100),XMLContent.query('/IDMSDocument/DocumentContent/Attribute[@Name="Публикa"]/Value/Value')),'</Value>','') ,'<Value>','') as Vpublika,
REPLACE( REPLACE (CONVERT(varchar(100),XMLContent.query('/IDMSDocument/DocumentContent/Attribute[@Name="Дата"]/Value/Date')),'</Date>','') ,'<Date>','') as VData,
REPLACE( REPLACE (CONVERT(varchar(100),XMLContent.query('/IDMSDocument/DocumentContent/Attribute[@Name="Вътрешен №"]/Value/Value')),'</Value>','') ,'<Value>','') as VVatreshen
REPLACE( REPLACE (CONVERT(varchar(100),XMLContent.query('/IDMSDocument/DocumentContent/Attribute[@Name="ДатаIn"]/Value/Date')),'</Date>','') ,'<Date>','') as VDataIn,
FROM @CTE;

SELECT 
PRI.DocumentNo as DOCUMENTNO,
PRI.VData as DATA,
PRI.VVatreshen as VATRESHEN,
SEK.DocumentNo as DocumentNo2,
SEK.VDataIn as VData2,
SEK.VVatreshen as VVatreshen
from @TBL as PRI LEFT JOIN @TBL as SEK ON (PRI.VData = SEK.VDataIn)
WHERE (PRI.Vpublika = 'Да') 

1 个答案:

答案 0 :(得分:2)

您是否尝试过使用CTEs而不是表格?

WITH cte AS (
  SELECT DocumentID,DocumentNo,CAST(REPLACE(CAST(content AS NVARCHAR(MAX)),'utf-8','utf-16') AS XML) AS XMLContent 
  FROM MainSQLTable   
  WHERE DOCTYPEID = 2
),
tbl AS (
  SELECT DocumentID,DocumentNo, 
         REPLACE( REPLACE (CONVERT(varchar(100),XMLContent.query('/IDMSDocument/DocumentContent/Attribute[@Name="Публикa"]/Value/Value')),'</Value>','') ,'<Value>','') as Vpublika,
         REPLACE( REPLACE (CONVERT(varchar(100),XMLContent.query('/IDMSDocument/DocumentContent/Attribute[@Name="Дата"]/Value/Date')),'</Date>','') ,'<Date>','') as VData,
         REPLACE( REPLACE (CONVERT(varchar(100),XMLContent.query('/IDMSDocument/DocumentContent/Attribute[@Name="Вътрешен №"]/Value/Value')),'</Value>','') ,'<Value>','') as VVatreshen,
         REPLACE( REPLACE (CONVERT(varchar(100),XMLContent.query('/IDMSDocument/DocumentContent/Attribute[@Name="ДатаIn"]/Value/Date')),'</Date>','') ,'<Date>','') as VDataIn
  FROM cte
)
SELECT 
PRI.DocumentNo as DOCUMENTNO,
PRI.VData as DATA,
PRI.VVatreshen as VATRESHEN,
SEK.DocumentNo as DocumentNo2,
SEK.VDataIn as VData2,
SEK.VVatreshen as VVatreshen
from tbl as PRI
LEFT JOIN tbl as SEK ON (PRI.VData = SEK.VDataIn)
WHERE (PRI.Vpublika = 'Да')