如何将此查询转换为linq

时间:2014-11-04 18:47:59

标签: sql linq

嗨请让我知道如何将此查询转换为linq,实际上我需要从sql server创建动态数据透视表我已完成此查询但我无法将此查询保存在我的sql server中与视图或函数相同或所以我想从我的实体模式中使用此查询的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)

1 个答案:

答案 0 :(得分:0)

我找到了一种简单的方法,我可以使用存储过程替换linq等来实现此目的:

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