获取在EXEC()中执行的动态PIVOT结果到varchar变量

时间:2019-06-11 05:51:46

标签: json sql-server tsql pivot exec

下面的代码创建一个JSON输出。

  

请注意:#Person表中的值是动态生成的。调用包含以下代码段的存储过程后,C#代码将输出识别为JSON,尽管它看起来像VARCHAR。我需要将输出JSON设为string(VARCHAR)因为无法基于#Names返回的值来动态生成C#模型。

DROP TABLE #Names
DROP TABLE #PersonInfo    

CREATE TABLE #Names (ID INT,Name VARCHAR(MAX))
CREATE TABLE #PersonInfo (ID INT,NameID INT,Subject VARCHAR(100),Marks INT)

INSERT INTO #Names VALUES (1,'Paul');
INSERT INTO #Names VALUES (2,'John');
INSERT INTO #Names VALUES (3,'Tayler');

INSERT INTO #PersonInfo VALUES (1,1,'Maths',95);
INSERT INTO #PersonInfo VALUES (2,2,'Science',32);
INSERT INTO #PersonInfo VALUES (3,3,'History',23);
INSERT INTO #PersonInfo VALUES (4,2,'Maths',32);
INSERT INTO #PersonInfo VALUES (5,3,'Science',60);
INSERT INTO #PersonInfo VALUES (6,1,'Music',60);

DECLARE @DynamicCols NVARCHAR(MAX) = '';
DECLARE @pvt NVARCHAR(MAX) = '';
DECLARE @SQLQuery NVARCHAR(MAX) = '';

SELECT @DynamicCols +=  ', SUM(' +QUOTENAME([Name])+') AS '+[Name] FROM #Names;
SET @DynamicCols = STUFF(@DynamicCols,1,1,'')
SELECT @pvt +=  ', ' +QUOTENAME([Name]) FROM #Names;
SET @pvt = STUFF(@pvt,1,1,'')

EXEC ('
SELECT [Subject],' + @DynamicCols+'
FROM (SELECT [NameID], [Subject], [Marks] FROM #PersonInfo) a
INNER JOIN #Names b ON a.NameID = b.ID
PIVOT 
(
  SUM([Marks])
  FOR [Name] IN ('+ @pvt+')
)   PIV
GROUP BY [Subject] FOR JSON AUTO, INCLUDE_NULL_VALUES');

结果

[{"Subject":"History","Paul":null,"John":null,"Tayler":23},{"Subject":"Maths","Paul":95,"John":32,"Tayler":null},{"Subject":"Music","Paul":60,"John":null,"Tayler":null},{"Subject":"Science","Paul":null,"John":32,"Tayler":60}]

DAL层中的C#代码

public string GetMarks(string partyRoleIdList)
  {
   return _context.Query<string>(usp_GetMarks, new { IdList }).SingleOrDefault();
  }

是否可以将执行的值(EXEC())转换为VARCHAR(MAX)

1 个答案:

答案 0 :(得分:0)

您可以轻松测试FOR JSON的结果是否为NVARCHAR(MAX)字符串:

exec sp_describe_first_result_set N'
SELECT *
FROM
(
    VALUES(''[a'')
) DS(col)
FOR JSON AUTO
';

赞这个:

is_hidden   column_ordinal  name    is_nullable system_type_id  system_type_name    max_length  precision   scale   collation_name
0   1   JSON_F52E2B61-18A1-11d1-B105-00805F49916B   1   231 nvarchar(max)   -1  0   0   SQL_Latin1_General_CP1_CI_AS

它是字符串,因此您可以轻松地将其转换为VARCHAR(MAX)或其他内容:

EXEC ('
SELECT CAST(
(
SELECT [Subject],' + @DynamicCols+'
FROM (SELECT [NameID], [Subject], [Marks] FROM #PersonInfo) a
INNER JOIN #Names b ON a.NameID = b.ID
PIVOT 
(
  SUM([Marks])
  FOR [Name] IN ('+ @pvt+')
)   PIV
GROUP BY [Subject] FOR JSON AUTO, INCLUDE_NULL_VALUES)
 AS VARCHAR(400))');