当前位置:K88软件开发文章中心编程语言SQLSQL01 → 文章内容

强大的sql server数据库的功能

减小字体 增大字体 作者:wangsdong     来源:asp编程网  发布时间:2018-12-30 9:14:34

数据库设计不合理真的太麻烦了。公司数据库中的用户表只用来保存产品分类,原程序员使用的方法是将这些分类放到同一个字段中。如下:

表test,里面的内容是
id 
 
 
text1

 
 
a1,a4,a5,a2

 
 
a,b,c

 
 
11,2,h
以前使用的过程中什么问题都没有,但现在公司要求这些分类可以让用户自己设定它的顺序。这样麻烦来了,如何让用户随意设置顺序?本以为增加一个字段,里面放顺序,如(3,2,1,4),试了很久,又出来3,2,1,4如何排序问题,还有原来数据库中原有的数据怎么办。

最后的解决办法是,将这些分类放到另一个表pclass中。
表pclass,字段名
id userid(对应test中的id字段) classid(text1中的某一项) class_order(顺序)

由test中的数据,向pclass中插入数据
我想得到的结果是:
pclass表
id userid classid class_order
1 1 a1 1
2 1 a4 2
3 1 a5 3
4 1 a2 4
5 2 a 1
6 2 b 2
7 2 c 3
8 3 11 1
9 3 2 2
10 3 h 3

感谢ai_li7758521帮助,终于很好的解决了
Create table test(id int,text1 nvarchar(100))
Insert test
select 1,N'a1,a4,a5,a2' union all
select 2,N'a,b,c' union all
select 3,N'11,2,h'
Go

create table pclass(id int identity,userid int,classid nvarchar(10),class_order int)

insert pclass
select userid,classid,class_order=rank() over(partition by userid order by num )
from(
 
 
 
select
 
 
 
 
 
 
userid=a.ID,classid=substring(a.text1,b.ID,charindex(',',a.text1+',',b.ID)-b.ID),num=b.ID
 
 
 
from
 
 
 
 
 
 
 
test a,(select ID=number from master..spt_values where type='P') b
 
 
 
where
 
 
 
 
 
 
 
charindex(',',','+a.text1,b.ID)=b.ID
) A

select * from pclass
/*
id 
 
 
 
 
 
 
 
 
userid 
 
 
 
 
classid 
 
 
class_order
----------- ----------- ---------- -----------

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 
a1 
 
 
 
 
 
 
 
1

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 
a4 
 
 
 
 
 
 
 
2

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 
a5 
 
 
 
 
 
 
 
3

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 
a2 
 
 
 
 
 
 
 
4

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
1

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
2

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
3

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 
11 
 
 
 
 
 
 
 
1

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
2
10 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
3

(10 行受影响)*/

sql server 的功能太强大了。



强大的sql server数据库的功能