求一存储过程,或者方法
我有4个表,大概结构如下,每一个表的ID是下一个表的外键。现在想通过一条SQL语句生成一个dataset里面有4个datatable。不知道SQL怎么写。求帮助。
比如:
sql:
select * from a(这里面查询出来的ID为第2个SQL语句的条件)
select * from b where aid=a.id??(这里面查询出来的ID为第3个SQL语句的条件)
select * from c where bid=b.id??(这里面查询出来的ID为第4个SQL语句的条件)
select * from d where cid=c.id??
A
ID content
B
ID AID content
C
ID BID content
D
ID CID conent
[解决办法]
SELECT *
FROM a t1
INNER JOIN b t2 ON t1.id=t2.aid
INNER JOIN c t3 ON t2.id=t3.bid
INNER JOIN d t4 ON t3.id=t4.cid
select * from a
select * from b where aid in (select id from a)
select * from c where bid in (select id from b)
select * from d where cid in (select id from c)
--字段名写错了,参考如下:
select * from a
select * from a INNER JOIN b ON a.id=b.aid
select * from a INNER JOIN b ON a.id=b.aid INNER JOIN c ON b.id=c.bid
select * from a INNER JOIN b ON a.id=b.aid INNER JOIN c ON b.id=c.bid INNER JOIN d ON d.cid=c.id
CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
AS
BEGIN
SELECT * FROM A
SELECT * FROM B
INNER JOIN A
ON B.ID=A.ID
SELECT * FROM C
INNER JOIN B
ON B.ID=C.ID
INNER JOIN A
ON B.ID=A.ID
SELECT * FROM D
INNER JOIN C
ON D.ID=C.ID
INNER JOIN B
ON B.ID=C.ID
INNER JOIN A
ON B.ID=A.ID
END
GO
create proc proc_test @id int
as
set nocount on
select * from a where id=@id
select * from a inner join b on a.id=b.aid where a.id=@id
select * from a inner join b on a.id=b.aid
inner join c on b.id=c.bid where a.id=@id
select * from a inner join b on a.id=b.aid
inner join c on b.id=c.bid inner join d on d.cid=c.id where a.id=@id
go