SQL Server sql循环遍历列表并将记录插入列中

ahy6op9u  于 2022-12-03  发布在  其他
关注(0)|答案(2)|浏览(242)

我想循环遍历一个列表,将每一项插入一列,并迭代1000次。2我是一个SQL新手-有人能帮我吗?
目前为止我所拥有的:

DECLARE @Counter INT 
DECLARE @myList varchar(100)

SET @Counter = 0
SET @myList = 'temp,humidity,dewpoint'

WHILE (@Counter <= 1000)
BEGIN
    INSERT INTO [DBO].[tbl_var] (VariableNames)
    VALUES (@myList)

    SET @Counter  = @Counter  + 1
END

我得到这个错误:
无法将值NULL插入到表'master.DBO.tbl_var'的列'VariableNames'。该列不允许空值INSERT失败
我所期望的
VariableNames

1. temp
2. humidity
3. dewpoint
4. temp
5. humidity
6. dewpoint

依此类推,直到完成列表的1000次迭代

6pp0gazn

6pp0gazn1#

如果你想对每个值进行INSERT运算1,000次,那么就使用VALUES表结构和CROSS JOIN来计算包含1,000行的计数。我在下面的解决方案中使用了内联计数:

USE YourUserDatabase;
GO

WITH N AS(
    SELECT N
    FROM (VALUES(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL),(NULL))N(N)),
Tally AS(
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS I
    FROM N N1, N N2, N N3) --1,000 rows
INSERT INTO dbo.tbl_var (VariableNames)
SELECT V.VariableName
FROM (VALUES('temp'),
            ('humidity'),
            ('dewpoint'),
            ('temp'),
            ('humidity'),
            ('dewpoint'))V(VariableName)
     CROSS JOIN Tally T;
g2ieeal7

g2ieeal72#

我还没有测试过,但是应该可以用。你可以使用STRING_SPLIT函数https://learn.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql?view=sql-server-ver16

DECLARE @Counter INT =1
    DECLARE @myList varchar(100)    
    SET @Counter=1
    SET @myList = 'temp,humidity,dewpoint'
    CREATE TABLE #TEMP (value varchar(255),cardinal Int)
    INSERT INTO #TEMP(value,cardinal)
    SELECT * FROM STRING_SPLIT(@myList, ',',1);

WHILE ( @Counter <= 1000)
BEGIN
    INSERT INTO  [DBO].[tbl_var] (VariableNames)
    SELECT value from #TEMP WHERE cardinal =@counter
    SET @Counter  = @Counter  + 1
END

相关问题