如何按某一字段内容把一个表拆分成多个表?
有表如下:
ID NAME CLASS
1 AA II
2 BB IV
3 AB IV
4 AC II
5 CC IX
6 SS II
7 AS IX
8 ES IX
---------------------
用什么方法可以吧上的表按照class的内容分成多个表
结果如下:
ID NAME CLASS
1 AA II
4 AC II
6 SS II
--------------------
ID NAME CLASS
2 BB IV
3 AB IV
--------------------
ID NAME CLASS
5 CC IX
7 AS IX
8 ES IX
------解决方案--------------------insert into table1 select * from tablename where class= 'II '
insert into table2 select * from tablename where class= 'IV '
insert into table3 select * from tablename where class= 'IX '
------解决方案--------------------DECLARE @CLASS sysname, @s nvarchar(4000)
DECLARE tb CURSOR LOCAL
FOR
SELECT DISTINCT
CLASS
FROM 你的表
OPEN tb
FETCH tb INTO @CLASS
WHILE @@FETCH_STATUS = 0
BEGIN
SET @s = N '
SELECT *
INTO ' + QUOTENAME( 'tb_ ' + @CLASS) + N ' -- 生成的表名为: tb_ <CLASS> , 根据需要自行调整
FROM 你的表
WHERE CLASS = @CLASS
'
EXEC sp_executesql @s, N '@CLASS sysname ', @CLASS
FETCH tb INTO @CLASS
END
CLOSE tb
DEALLOCATE tb
------解决方案--------------------