2014-11-04 145 views
-1

嗨請讓我知道如何將此查詢轉換爲linq,實際上我需要從sql server創建動態數據透視表我已完成此查詢但我無法將此查詢保存到我的sql服務器與視圖或功能相同,等等,所以我想從我的實體模式中使用這個查詢的linq veersion。如何將此查詢轉換爲linq

TNX

DECLARE @ColumnsTable TABLE ([ColumnName] VARCHAR(50)); 

INSERT INTO @ColumnsTable ([ColumnName]) 
SELECT DISTINCT '[' + CONVERT(nvarchar(50), Unit) + ']' 
FROM dbo.MeterValueView; 

DECLARE @PivotColumns VARCHAR(MAX), @TotalColumn VARCHAR(MAX), @SQL VARCHAR(MAX); 

SET @PivotColumns = (SELECT STUFF((SELECT DISTINCT ', ' + CONVERT(nvarchar(50), [ColumnName]) 
            FROM @ColumnsTable 
            FOR XML PATH('')), 1, 2, '')); 
SET @TotalColumn = (SELECT STUFF((SELECT DISTINCT ' + ISNULL(' + CONVERT(nvarchar(50), [ColumnName]) + ', 0)' 
            FROM @ColumnsTable 
            FOR XML PATH('')), 1, 3, '')); 
SET @SQL = 'SELECT *, (' + @TotalColumn + ') AS [Total] 
FROM (SELECT [Serial], 
       [Unit], 
       [Value] 
     FROM [MeterValueView]) AS t 
     PIVOT (MAX([Value]) 
      FOR [Unit] IN (' + @PivotColumns + ')) AS p;'; 

EXEC(@SQL) 
+0

任何努力這麼遠? – AgentFire 2014-11-04 19:01:27

+0

linq中沒有與SQL的'PIVOT'等價的東西。爲什麼你不能用這個存儲過程? – Magnus 2014-11-04 19:12:43

回答

0

我發現一個簡單的方法,我可以使用存儲過程代替LINQ等爲getiing這個目的:

CREATE PROC MeterValuesView 

AS 
BEGIN 

DECLARE @ColumnsTable TABLE ([ColumnName] VARCHAR(50)); 

INSERT INTO @ColumnsTable ([ColumnName]) 
SELECT DISTINCT '[' + CONVERT(nvarchar(50), Unit) + ']' 
FROM dbo.MeterValueView; 

DECLARE @PivotColumns VARCHAR(MAX), @TotalColumn VARCHAR(MAX), @SQL VARCHAR(MAX); 

SET @PivotColumns = (SELECT STUFF((SELECT DISTINCT ', ' + CONVERT(nvarchar(50), [ColumnName]) 
            FROM @ColumnsTable 
            FOR XML PATH('')), 1, 2, '')); 
SET @TotalColumn = (SELECT STUFF((SELECT DISTINCT ' + ISNULL(' + CONVERT(nvarchar(50), [ColumnName]) + ', 0)' 
            FROM @ColumnsTable 
            FOR XML PATH('')), 1, 3, '')); 
SET @SQL = 'SELECT *, (' + @TotalColumn + ') AS [Total] 
FROM (SELECT [Serial], 
       [Unit], 
       [Value] 
     FROM [MeterValueView]) AS t 
     PIVOT (MAX([Value]) 
      FOR [Unit] IN (' + @PivotColumns + ')) AS p;'; 

EXEC(@SQL) 

END