TSQL - 为多个插入

时间:2017-12-17 22:48:16

标签: sql sql-server tsql

Declare  @table1 TABLE([Len] int, Values Nvarchar(1000) );

Declare  @table2 (sqlInsert NVARCHAR(MAX))
Declare @sql = "Insert Into @table2 Values ";

-- 1. Table store Values
INSERT INTO @table1 ([Len], Values)
VALUES (2, 'AB'), (3, 'BCD'), (4, 'CACA'), (2, 'DA'), (3, 'FAE'), (4, 'FAE'), (6, 'IGOALS'), (2, 'HA');

SELECT * FROM @table1

我想从值构建动态SQL多插入@table1

示例:

@sql = "Insert Into @table2 Values ('AB'), ('BCD'), ('CACA'), ('DA'), ('FAE'), ('FERE'), ('IGOALS'), ('HA')";
EXEC sp_executesql (@sql);

但是,Nvarchar的最大值为4000.这就是为什么,我认为我应该从@table1

中连接字符串值

与此表类似(示例范围长度> 5,然后合并字符串值)

  Index | Sum(Len) | Name        | Description
--------+----------+-------------+--------------------------------   
    1   |   9      | AB,BCD,CACA | (Explain: First Sum(Len) > 5, Merge String)
    2   |   9      | DA,FAE,FAE  | (Explain:Second Sum(Len) > 5, Merge String)
    3   |   6      | IGOALS      | (Explain:Third, Sum(Len) > 5, Merge String)
    4   |   2      | HA          | (Explain:Last, still one last step)

请帮助我解决从@ table1中的值到@ table2这样的表的问题。 或者您有其他解决方案,建议我。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

不使用table2和列Len的另一种解决方案可能就是这个。希望这可以提供帮助。

Declare  @table1 TABLE([Len] int, [Values] Nvarchar(1000) );

Declare  @table2 TABLE (sqlInsert NVARCHAR(MAX))
Declare @sql NVARCHAR(MAX) = 'Insert Into @table2 Values ';

--1. Table store Values
INSERT INTO @table1 ([Len], [Values])
VALUES (2, 'AB'), (3, 'BCD'), (4, 'C''ACA'), (2, 'DA'), (3, 'FAE'), (4, 'FAE'), (6, 'IGOALS'), (2, 'HA');

SELECT * FROM @table1
-----
DECLARE @insert NVARCHAR(4000) = NULL
      , @Values NVARCHAR(4000);

DECLARE @maxLen INT = 4000 - LEN(@sql) - 2
DECLARE cur CURSOR LOCAL FAST_FORWARD FOR
SELECT '''' + REPLACE([Values], '''', '''''') + '''' from @table1;
print @maxLen
OPEN cur

FETCH NEXT FROM cur INTO @Values
WHILE @@FETCH_STATUS = 0
BEGIN
    IF LEN(@insert) + LEN(@Values) > @maxLen
       BEGIN
            SET @insert = @sql + '(' + @insert + ')'
            print  @insert  
            --INSERT INTO @table2 VALUES (@insert)
            --EXEC sp_executesql (@insert);     
            SET @insert = @Values;
       END
    ELSE
       BEGIN
            SET @insert = isnull(@insert + ',', '') + @Values
       END

    FETCH NEXT FROM cur INTO @Values
END

SET @insert = @sql + '(' + @insert + ')'
print  @insert  
--INSERT* INTO @table2 VALUES (@insert)
--EXEC sp_executesql (@insert);     

CLOSE cur

DEALLOCATE cur 


--SELECT * FROM @table2