1. 程式人生 > >從表中插入資料到另外一張表

從表中插入資料到另外一張表

 

方法一:

程式碼

1 select into 和 insert into select 兩種表複製語句
2 select * into destTbl from srcTbl
3
4 insert into destTbl(fld1, fld2) select fld1, 5 from srcTbl
5
6 以上兩句都是將 srcTbl 的資料插入到 destTbl,但兩句又有區別的。
7
8 第一句(select into from)要求目標表(destTbl)不存在,因為在插入時會自動建立。
9
10 第二句(insert into select from)要求目標表(destTbl)存在,由於目標表已經存在,所以我們除了插入源表(srcTbl)的欄位外,還可以插入常量
11
12

方法二:

程式碼

1 --定義資料
2 DECLARE @srcTitle varchar(500),
3 @srcTime datetime,
4 @srcContent varchar(max)
5 --定義遊標
6 DECLARE Mem_Cursor CURSOR FOR
7 --從源表中獲取資料
8 SELECT [title],[fbtime],[content] FROM [fjch].[dbo].[bszn]
9
10 --開啟遊標
11 OPEN Mem_Cursor
12
13 --將獲取資料新增到記憶體表中
14 FETCH NEXT FROM Mem_Cursor INTO @srcTitle,@srcTime,@srcContent
15
16 WHILE @@FETCH_STATUS=0
17 BEGIN
18 --將資料插入到新表中
19 INSERT INTO [FJBSMDB].[dbo].[Scms_news]
20 ([title]
21 ,[time]
22 ,[bigclassname]
23 ,[content]
24 ,[hits]
25 ,[author]
26 ,[url]
27 ,[smallclass]
28 ,[ding]
29 ,[dig]
30 ,[zhaiyao]
31 ,[checked]
32 ,[Permissions]
33 ,[thirdclass]
34 ,[reasons]
35 ,[IsShowInHome]
36 ,[IsRolling]
37 ,[IsTop]
38 ,[IsTopOrder]
39 ,[IsInProvince])
40 VALUES
41 (@srcTitle
42 ,@srcTime
43 ,3
44 ,@srcContent
45 ,0
46 ,'福建省測繪局' --原辦事指南沒來源
47 ,'Articls/200912/'+convert( varchar(8),cast(rand(checksum(newid()))*100000000 as int ))+'.html'
48 ,14
49 ,0
50 ,0
51 ,''
52 ,4
53 ,''
54 ,0
55 ,''
56 ,'False'
57 ,'False'
58 ,'False'
59 ,0
60 ,'False')
61
62 FETCH NEXT FROM Mem_Cursor INTO @srcTitle,@srcTime,@srcContent
63 END
64
65 --關閉遊標
66 CLOSE Mem_Cursor
67 --刪除臨時表
68 DEALLOCATE Mem_Cursor