Sql Server - 作为数组的Integer数据类型的列的格式查询结果

时间:2018-01-16 10:54:41

标签: arrays json sql-server stringify sql-server-json

当我运行以下查询时,结果类似于下面屏幕截图中提供的结果。

DECLARE @numArray VARCHAR(50) = '[1,2,45,1,21,45,32,564,48,56,98,87]';

SELECT  value AS Number  FROM OPENJSON(@numArray)

enter image description here

我很好奇是否有可能以相反的方式。我的意思是,如果我有这样的查询:

Select Number from Table_name

那么它应该提供如下结果:[1,2,45,1,21,45,32,564,48,56,98,87]

我尝试使用For JSON,但它只返回JSON数组。(不是int数组)

现在我知道还有其他方法可以做到,我也做过。但有没有办法使用Sql Server JSON函数?

谢谢

修改 目前我正在使用东西来连接所有行。但我想知道是否有类似FOR JSON PATH的内容。

2 个答案:

答案 0 :(得分:1)

此代码可能对您有所帮助,下面是示例数据

IF OBJECT_ID('tempdb..#SampleData') IS NOT NULL
DROP TABLE #SampleData
;WITH Cte( SapmleData )
AS
(
SELECT 1    UNION ALL
SELECT 2    UNION ALL
SELECT 45   UNION ALL
SELECT 1    UNION ALL
SELECT 21   UNION ALL
SELECT 45   UNION ALL
SELECT 32   UNION ALL
SELECT 564  UNION ALL
SELECT 48   UNION ALL
SELECT 56   UNION ALL
SELECT 98   UNION ALL
SELECT 87   
)
SELECT * INTO #SampleData FROM Cte

SELECT * FROM #SampleData

在sql server中使用stuff()

SELECT '['+STUFF((SELECT DISTINCT ','+ CAST(SapmleData AS VARCHAR(10))   FROM #SampleData
FOR XML PATH ('')),1,1,'') +']' AS Expectedcolumn   

SapmleData
----------
1
2
45
1
21
45
32
564
48
56
98
87

Expectedcolumn
----------------
[1,2,21,32,45,48,56,564,87,98]

答案 1 :(得分:0)

尝试使用XML。喜欢这个

;WITH CTE
AS
(
    SELECT
       Val = 1

    UNION ALL

    SELECT
       Val = Val+1
       FROM CTE
          WHERE Val < 10
)
SELECT
    List = '['+SUBSTRING(List,1,LEN(List)-1)+']'
    FROM 
    (
       SELECT
         CAST(Val AS VARCHAR(20))+',' as [text()]
       FROM CTE
       FOR XML PATH('')
    )L(List)