动态选择SQL选择语句

时间:2019-06-14 12:07:15

标签: sql sql-server tsql

我想实现什么? 将动态列和值附加到select语句。

这是我到目前为止所做的:

DECLARE @json_sql NVARCHAR(MAX) = ''

WHILE(@a <= @aCount)
BEGIN

DECLARE @_Sql NVARCHAR(MAX) = NULL
DECLARE @col_name NVARCHAR(5) = NULL
DECLARE @col_value NVARCHAR(150) = NULL

SET @col_name = (SELECT Term FROM @subjectcummulative  WHERE row_id = @a AND SubjectId = @p_subjectId)
SET @col_value = (SELECT Average FROM @subjectcummulative  WHERE row_id = @a AND SubjectId = @p_subjectId)



SET @json_sql = @json_sql + '","' + @col_name +'":"' + ',' + @col_value + ','

SET @a = @a + 1
END;

最后,附加字符串以选择并输出为JSON:

    DECLARE @scoreSheet TABLE(ScoreSheet NVARCHAR(MAX))

INSERT @scoreSheet SELECT CONCAT('[',
         STUFF(
               (SELECT
                    CONCAT(',{"SubjectName":"', SubjectName + @json_sql + '"}')
                FROM #scoreSheet
                FOR XML PATH('')
                ), 1, 1, '')
         , ']') AS ScoreSheet

SELECT * FROM @scoreSheet;

0 个答案:

没有答案