存储过程代码
CREATE PROC Proc_JsonConvertTable(@JSON VARCHAR(MAX))
AS
--JSON测试数据
--SET @JSON='[{name:张三,age:18,hobby:打篮球},{name:李四,age:30,hobby:唱歌},{name:王五,age:33,hobby:跳舞}]';
--JSON测试数据处理
SET @JSON=REPLACE(@JSON,'[','');
SET @JSON=REPLACE(@JSON,']','');
SET @JSON=REPLACE(@JSON,'},{','}-*{');
DECLARE @ColName VARCHAR(15),
@ColName_CN VARCHAR(15),
@Value VARCHAR(100); --取列名
SELECT TOP 1
@Value=Value
FROM dbo.SplitString(@JSON,'-*',1);
DECLARE @Value2 VARCHAR(100);
SET @Value2=@Value;
SET @Value2=REPLACE(@Value2,':',',');
SET @Value2=REPLACE(@Value2,'"','');
SET @Value2=REPLACE(@Value2,'{','');
SET @Value2=REPLACE(@Value2,'}','');
DECLARE cr1 CURSOR
FOR
SELECT Value
FROM dbo.SplitString(@Value2,',',1);
OPEN cr1;
DECLARE @col VARCHAR(50),
@createSQL VARCHAR(500);
--拼接创建临时表的SQL
SET @createSQL='CREATE TABLE #TABLE (';
FETCH NEXT FROM cr1 INTO @col; DECLARE @forindex INT;
SET @forindex=2;
WHILE @@FETCH_STATUS=0
BEGIN
IF @forindex%2=0
BEGIN
SET @createSQL=@createSQL+@col+' VARCHAR(50) NOT NULL,';
SET @JSON=REPLACE(@JSON,'"','');
SET @JSON=CONVERT(VARCHAR(500),REPLACE(@JSON,':','ACC'));
SET @JSON=REPLACE(@JSON,@col+'ACC','');
END;
SET @forindex=@forindex+1;
FETCH NEXT FROM cr1 INTO @col; END;
CLOSE cr1;
DEALLOCATE cr1;
SET @createSQL=SUBSTRING(@createSQL,0,LEN(@createSQL));
SET @createSQL=@createSQL+');';
PRINT @createSQL; --处理JSON数据,并将数据插入到临时表
DECLARE cr CURSOR
FOR
SELECT Value
FROM dbo.SplitString(@JSON,'-*',1);
OPEN cr;
FETCH NEXT FROM cr INTO @Value; WHILE @@FETCH_STATUS=0
BEGIN
SET @Value=REPLACE(@Value,'{','');
SET @Value=REPLACE(@Value,'}','');
SET @Value=REPLACE(@Value,'"',''); PRINT @Value;
SET @col=(SELECT ''''+Value+''''+','
FROM SplitString(@Value,',',1)
FOR XML PATH(''));
SELECT @col=SUBSTRING(@col,0,LEN(@col));
PRINT @col;
SET @createSQL=@createSQL+'INSERT INTO #TABLE SELECT '+@col+';';
FETCH NEXT FROM cr INTO @Value;
END;
SET @createSQL=@createSQL+'SELECT * FROM #TABLE;';
PRINT @createSQL;
CLOSE cr;
DEALLOCATE cr; --执行SQL,并输出结果
EXEC(@createSQL);
测试代码
EXEC Proc_JsonConvertTable @JSON='[{name:蔡徐坤,age:18,hobby:唱、跳、Rap、篮球},{name:李四,age:30,hobby:唱歌},{name:王五,age:33,hobby:跳舞}]'
测试结果