IF ( @departmentId IS NOT NULL )
BEGIN
SET @sql = @sql + 'WITH BM
AS ( SELECT id ,
BMMingCheng ,
P_id
FROM BuMen
WHERE id = '
+ CONVERT(VARCHAR(4), @departmentId)
+ '
UNION ALL
SELECT BuMen.id ,
BuMen.BMMingCheng ,
BuMen.P_id
FROM BuMen
INNER JOIN BM ON dbo.BuMen.P_id = BM.id)'
END
相当于一个临时视图,如上定义为BM,之后可以再sql语句中使用BM当做一个表一样
谢谢