Get portion of a table and get 2 tables 1 being updated SQL Server
I have a table like:
id NameColumn
-------------
1 var
2 var2
3 var3
4 var4
5 var5
... ...
n varn
Is there a Wa开发者_JS百科y I can get a portion of this table, say, the first 3, and get to tables (the second one in the field 'id' is updated) like:
TABLE1:
id NameColumn
-------------
1 var
2 var2
3 var3
TABLE2:
id NameColumn
-------------
1 var4
2 var5
3 var6
4 var7
... ...
n varn
Have a look at this example script. Is this what you had in mind?
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
Try this..
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>
)
To insert into new table try:
INSERT INTO <YOUR_NEW_TABLE>
SELECT *
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY ID) AS ID,
NameColumn
FROM <YOUR_TABLE>
)
精彩评论