原数据结构
需要的结果
SQL语句
1
2
if exists(select * from sysobjects where id = object_id('Page') and type='u' )
3
drop table Page
4
5
create table Page
6
(
7
PageID int primary key,
8
PageText nvarchar(4000)
9
)
10
11
declare @bookid nvarchar(10)
12
declare @sql nvarchar(4000)
13
14
15
--定义游标
16
DECLARE Book_Cursor CURSOR FOR SELECT BookID From BookInfo order by bookid
17
open Book_Cursor
18
FETCH NEXT FROM Book_Cursor Into @bookid
19
WHILE @@FETCH_STATUS = 0
20
BEGIN
21
--print @bookid
22
23
set @sql='
24
insert into Page
25
SELECT *
26
FROM(
27
SELECT DISTINCT pageid FROM Areainfo_'+@bookid+'
28
)AA
29
OUTER APPLY(
30
SELECT
31
[values]= STUFF(REPLACE(REPLACE(
32
(
33
SELECT [Text] =
34
CASE
35
WHEN [TextReplace] IS NOT NULL THEN [TextReplace]
36
WHEN [TextReceive] IS NOT NULL THEN [TextReceive]
37
WHEN [TextProfessor] IS NOT NULL THEN [TextProfessor]
38
WHEN [TextLandscape] IS NOT NULL THEN [TextLandscape]
39
WHEN [TextPortrait] IS NOT NULL THEN [TextPortrait]
40
WHEN [TextRecension] IS NOT NULL THEN [TextRecension]
41
WHEN [TextSecond] IS NOT NULL THEN [TextSecond]
42
ELSE [TextFirst]
43
END
44
FROM textinfo_'+@bookid+' as t left join Areainfo_'+@bookid+' as a ON a.areaid=t.areaid WHERE pageid = AA.pageid order by pageid
45
FOR XML AUTO
46
),''<t Text="'', ''''), ''"/>'', ''''), 1, 1,'''')
47
)N'
48
--print @sql
49
exec(@sql)
50
FETCH NEXT FROM Book_Cursor Into @bookid
51
end
52
close Book_Cursor
53
deallocate Book_Cursor
54
55
select * from page

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55
