SQL - 选择多行,然后将它们插入另一个表/数据库

时间:2018-03-21 14:16:19

标签: sql sql-server

我想选择多行,然后将它们插入另一个表/数据库。

我当前的查询仅适用于1个结果,我需要它才能使用,例如,100:

DECLARE @var INT;

SELECT
    @var = column
FROM
    database.dbo.table1

-- this will produce for example, 100 results

IF (@var IS NULL) -- which it is all 100 times
    INSERT INTO database.dbo.table2
        (column)
    VALUES
        (@var)

我该怎么做,甚至可以做到这一点?

我正在使用Microsoft SQL Server Management Studio 2016。

2 个答案:

答案 0 :(得分:3)

我假设你想要:

INSERT INTO database.dbo.table2(column)
    SELECT column
    FROM database.dbo.table1
    WHERE column IS NULL;

答案 1 :(得分:0)

You can use cursor for insert the data like below


DECLARE @var INT;
Declare AIX Cursor for 
SELECT  column FROM  database.dbo.table1;
Open AIX;
Fetch Next from AIX into  @var;
-- this will produce for example, 100 results
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@var IS  NULL) -- which it is all 100 times
    INSERT INTO database.dbo.table2
        (column)
    VALUES
            (@var)
FETCH NEXT FROM AIX 
    INTO @var;
END
CLOSE AIX;
DEALLOCATE AIX;