某知名IT公司上机测试题(我刚参加的)
某知名IT公司上机测试题(我刚参加的)
有MAIN和SUB两个表,字段如下
MAIN
A VARCHAR(36) PRIMARY KEY NOT NULL (为什么是varchar? 不理解)
B VARCHAR(36) NOT NULL
C CHAR(1) NULLABLER
SUB
D VARCHAR(36) PRIMARY KEY NOT NULL
A VARCHAR(36) FOREIGN KEY NOT NULL 和MAIN表的A关联
E INT
F INT
1)求以下视图
A B C D E F G
-- -- -- -- -- -- --
-- -- -- -- -- -- --
2) 对以上视图按照G列排序
注:G列的值有E,F(F>G)两列决定 G= E +(E+1) +(E+2)+...+F
数据库相关操作
我的解法:
1.分别求出当前两个表的最大主键ID
CREATE PROCEDURE dbo.selectmax
@flag int
AS
declare @max int
if @flag = 1
select @max = max(convert(int,A)) from MAIN
else
select @max = max(convert(int,D)) from SUB
--return @max
return @MAX
GO
2.向两个表插入数据
CREATE procedure dbo.insertAll
--@A int,
@B varchar(36),
@C char(1),
--@D int,
@E int,
@F int
as
-- 局部变量不能 用逗号分割
declare @temp int
declare @keyA int
declare @errorcount int
exec @temp = selectmax 1
set @keyA = @temp +1
insert into MAIN VALUES(convert(varchar(36),@keyA),@B,@C)
set @errorcount = @@error
if @errorcount =0
-- if 后有多条语句是 需用begin和end 包围
begin
exec @temp = selectmax 0
set @temp = @temp +1
insert into SUB values(convert(varchar(36),@temp),@keyA,@E,@F)
--print 'success'
return 1
end
else
--print 'fail'
return(0)
GO
3.创建显示视图
create view MAINSUBVIEW(A,B,C,D,E,F,G)
as
select MAIN.A,B,C,D,E,F,dbo.addsum(E,F) as G
from MAIN,SUB
where MAIN.A = SUB.A
4.修改视图(关键是修改E,F的时候,G的变化)
update MAINSUBVIEW
set f = 7,
e = 4
where a = 4;
另外 我自己还另建一个addsum() 函数 如下:
CREATE function addsum
(@from int,
@to int
)
returns int
as
begin
declare
@sum int,
@at int,
@temp int
set @sum = 0
set @temp = @from
set @at = @from
while @temp <= @to
begin
set @sum = @sum +@temp
set @temp = @temp +1
end
return (@sum)
end
GO
结果没被录取 为什么???
附:inner join & left outer join & right outer join
(两表之间的关联去掉)
******************************************************
select * from main
1 lanshh 0
2 xsl 1
3 sss 0
4 kkk 0
5 kkk 0
6 kkk 0
*******************************************************
select * from sub
1 1 3 7
2 2 4 6
3 3 6 8
4 4 1 7
5 6 1 10
6 7 1 3
*******************************************************
select main.a,b,c,d,sub.a,e,f
from MAIN left join SUB
on main.a = sub.a
1 lanshh 0 1 1 3 7
2 xsl 1 2 2 4 6
3 sss 0 3 3 6 8
4 kkk 0 4 4 1 7
5 kkk 0 NULL NULL NULL NULL
6 kkk 0 5 6 1 10
*******************************************************
select main.a,b,c,d,sub.a,e,f
from MAIN right join SUB
on main.a = sub.a
1 lanshh 0 1 1 3 7
2 xsl 1 2 2 4 6
3 sss 0 3 3 6 8
4 kkk 0 4 4 1 7
6 kkk 0 5 6 1 10
NULL NULL NULL 6 7 1 3
*******************************************************
select main.a,b,c,d,sub.a,e,f
from MAIN inner join SUB
on main.a = sub.a
1 lanshh 0 1 1 3 7
2 xsl 1 2 2 4 6
3 sss 0 3 3 6 8
4 kkk 0 4 4 1 7
6 kkk 0 5 6 1 10