CREATE OR ALTER PROCEDURE dbo.DynamicBulkUpInsert
@JsonData NVARCHAR(MAX)
AS
BEGIN
SET NOCOUNT ON;
-- Fix JSON formatting first
SET @JsonData = REPLACE(@JsonData, N',', N',');
-- 使用简单的字符串解析方法
DECLARE @TableName NVARCHAR(128), @Records NVARCHAR(MAX);
DECLARE @Start INT = 1;
WHILE @Start < LEN(@JsonData)
BEGIN
-- Find TableName
DECLARE @TableStart INT = CHARINDEX('"TableName":"', @JsonData, @Start);
IF @TableStart = 0 BREAK;
SET @TableStart = @TableStart + LEN('"TableName":"');
DECLARE @TableEnd INT = CHARINDEX('"', @JsonData, @TableStart);
SET @TableName = LOWER(SUBSTRING(@JsonData, @TableStart, @TableEnd - @TableStart));
-- Find INSJson
DECLARE @JsonStart INT = CHARINDEX('"INSJson":', @JsonData, @TableEnd);
IF @JsonStart = 0
BEGIN
SET @Start = @TableEnd + 1;
CONTINUE;
END
-- Extract JSON array
SET @JsonStart = @JsonStart + LEN('"INSJson":');
DECLARE @BracketCount INT = 0;
DECLARE @Pos INT = @JsonStart;
DECLARE @Char NCHAR(1);
WHILE @Pos <= LEN(@JsonData)
BEGIN
SET @Char = SUBSTRING(@JsonData, @Pos, 1);
IF @Char = N'[' SET @BracketCount = @BracketCount + 1;
ELSE IF @Char = N']' SET @BracketCount = @BracketCount - 1;
IF @BracketCount = 0
BEGIN
BREAK;
END
SET @Pos = @Pos + 1;
END
DECLARE @JsonEnd INT = @Pos;
SET @Records = SUBSTRING(@JsonData, @JsonStart, @JsonEnd - @JsonStart + 1)