今天为QA写一个报表,使用了存储过程,在里面定义了一个临时表, 然后向临时表插入数据,插入数据的顺序和临时表的字段定义的顺序不一样,结果出来的结果乱七八糟,查了半天也没有想到什么原因,后来突然想到是不是和顺序有关,修改了insert语句里面的字段插入顺序,问题搞定。
唉,不知道是我对SQL了解太少还是SQL server确实很烂。
例子如下:
DECLARE @TEMP_TABLE TABLE (id int,count int)
insert INTO @TEMP_TABLE
select x.id as id, count(x.id) as count
from xxx x group by x.id
insert INTO @TEMP_TABLE
select count(x.id) as count), x.id as id
from xxx x group by x.id
上面的那个insert可以工作,下面的不能,得到的结果和期望的是不一致的
(Visited 158 times, 1 visits today)
2008年5月8日 at 13:44
DECLARE @TEMP_TABLE TABLE (id int,count int)
insert INTO @TEMP_TABLE (count,id)
select count,id
from (
select 11 as count,1 as id union
select 22 as count,2 as id
)a
select * from @TEMP_TABLE
2008年5月8日 at 14:10
sql server的插入,和来源表的字段名是没有关系的,是按来源数据的排列顺序插入的,我感觉这是合理的,也是灵活的。这样可以从不同的数据源插入数据,比如:
DECLARE @TEMP_TABLE TABLE (id int,count int)
insert INTO @TEMP_TABLE
select 1,2
select * from @TEMP_TABLE