SQL语言if语句

来源:百度知道 编辑:UC知道 时间:2024/05/27 23:53:24
题目:查询1班的学生在2班有无老乡,有老乡则列出,无老乡则为NULL
二班的表
use pubs
go
create table jy0702(
学号 char(10) not null,
姓名 varchar(10),
性别 varchar(5),
出生日期 smalldatetime,
月消费 money,
工作 varchar(20),
月薪 money,
籍贯 varchar(50),
爱好 varchar(50));

一班的:
use pubs
go
create table jy0701(
学号 char(10) not null,
姓名 varchar(10),
性别 varchar(5),
出生日期 smalldatetime,
月消费 money,
工作 varchar(20),
月薪 money,
籍贯 varchar(50),
爱好 varchar(50));
我要IF语句的做法!谢谢!!

if exists(select * from jy0702 a,jy0701 b where a.籍贯=b.籍贯)
select a.籍贯 from jy0702 a,jy0701 b where a.籍贯=b.籍贯
else select null

感觉这么写简单一点吧

create procedure pro_student
@name varchar(20)
as
declare @jiguan varchar(20)
declare @count int
select @jiguan=籍贯 from jy0701 where 姓名=@name
while(1=1)
begin
select @count=count(*) from jy0702 where 籍贯=@jiguan
if(@count>0)
select * from jy0702 where 籍贯=@jiguan
else
print 'null'
break

end

declare laoxiang cursor for
select 籍贯 from jy0701
open laoxiang
declare @jiguan varchar(50)
while(@@fetch_status=0)
begin
fetch next from laoxiang into @jiguan
if @jiguan in (select 籍贯 from jy0702)
select * from jy0702 where 籍贯=@jiguan
end
close laoxiang