获取表的一部分并获得2个表1正在更新SQL Server

时间:2011-02-17 04:58:10

标签: sql-server-2008

我有一张表:

id NameColumn 
-------------
1  var
2  var2 
3  var3
4  var4
5  var5
...  ...
n  varn

有没有办法我可以得到这个表的一部分,比如前三个,然后到表(第二个字段'id'更新),如:

TABLE1:

id NameColumn 
-------------
1  var
2  var2 
3  var3

TABLE2:

id NameColumn 
-------------
1  var4
2  var5
3  var6
4  var7
...  ...
n  varn

2 个答案:

答案 0 :(得分:1)

看看这个示例脚本。这是你的想法吗?

DECLARE @Table1 TABLE(
        ID INT IDENTITY,
        Name VARCHAR(20)
)
DECLARE @Table2 TABLE(
        ID INT IDENTITY,
        Name VARCHAR(20)
)
INSERT INTO @Table1 (Name) SELECT 'A'
INSERT INTO @Table1 (Name) SELECT 'B'
INSERT INTO @Table1 (Name) SELECT 'C'
INSERT INTO @Table1 (Name) SELECT 'D'

DECLARE @N INT
SELECT  @N = 2

INSERT INTO @Table2
SELECT  Name
FROM    @Table1 t1 
WHERE   ID NOT IN   (
                        SELECT  TOP (@N)
                                ID
                        FROM    @Table1 
                        ORDER BY    ID
                    )
DELETE FROM @Table1
WHERE   ID NOT IN   (
                    SELECT  TOP (@N)
                            ID
                    FROM    @Table1 
                    ORDER BY    ID
                )

SELECT  *
FROM    @Table1
SELECT  *
FROM    @Table2

答案 1 :(得分:0)

试试这个..

TABLE1:

SELECT TOP 3 *
  FROM <YOUR_TABLE>
ORDER BY ID

TABLE2:

SELECT *
  FROM ( 
        SELECT ROW_NUMBER() OVER(ORDER BY ID) AS ID, 
               NameColumn
          FROM <YOUR_TABLE>
       )

要插入新表,请尝试:

INSERT INTO <YOUR_NEW_TABLE>
    SELECT *
      FROM ( 
            SELECT ROW_NUMBER() OVER(ORDER BY ID) AS ID, 
                   NameColumn
              FROM <YOUR_TABLE>
           )