天天看點

SQL Server 複制表結構以及資料,去除表中重複字段

SQL Server 複制表結構以及資料,去除表中重複字段

--複制另一個資料庫中的某張表的結構及資料

--select * from Test.dbo.TestTable(查詢表中所有資料)

--into [表名] 插入目前資料庫新表,如果沒有該表就建立

select * into TestCopy from Test.dbo.TestTable

--隻複制表結構(1!=1等價于1<>1,隻要where後的為false就可以)

--把查詢出的資料插入到新表,如果沒有資料就隻是複制表結構了

select * into TestCopy from Test.dbo.TestTable where 1!=1

--into #[表名] #代表臨時表

select * into #TestCopy from Test.dbo.TestTable

--複制某個字段到新表(字段名相同)

select TestID into TestCopy from Test.dbo.TestTable

--複制某個字段到新表(字段名不同)

--下面的寫法不正确,可能插入某一個字段時表必須存在

select TestID into TestCopy1(TestCopy1ID) from Test.dbo.TestTable

--複制某個字段到新表(重新命名字段名)

--在查詢時使用别名新表中的字段名是别名而不是本名

select TestID as TestCopyID into TestCopy1 from Test.dbo.TestTable

--上面是新表不存在的時候,當表存在時

insert into TestCopy1 select * from Test.dbo.TestTable

--插入一個字段的資料到新表(可以插入到别的字段中去)

insert into TestCopy1(TestName) select TestID from Test.dbo.TestTable

--複制同一張表中資料(沒有主鍵,複制的資料在上面不在下面)

insert into TestCopy(testID) select testName from TestCopy

--去除表中重複字段

--row_number() over 統計相同的字段并給每條資料加上一個标号,>1代表重複資料,删除掉>1的資料

delete t from

(select row_number() over (partition by testID,testName,price order by testID) as p1,* from TestCopy) as t

where t.p1>1

原文位址

https://www.cnblogs.com/privategardens/p/10761009.html