如何在SQL Server 2000中使用等效的CROSS APPLY?
我有一个函数返回传递的id的顶级父级。
ALTER Function [dbo].[fn_GetTopParentRiskCategory]
(
@RctId int
)
RETURNS @TEMP_TABLE TABLE
(
rctId int,
topParentRiskCat Varchar(100)
)
AS
BEGIN
DECLARE @PARENTID INT
DECLARE @GRANDPARENTID INT
DECLARE @CODE VARCHAR(100)
DECLARE @DESC VARCHAR(100)
DECLARE @PARENTCODE VARCHAR(100)
SELECT @PARENTID= rctParentID from RiskCategory where rctid=@RctId
SELECT @GRANDPARENTID= rctParentId from RiskCategory where rctid= @PARENTID
IF @GRANDPARENTID IS NULL
BEGIN
SELECT @CODE='ALL'
INSERT INTO @TEMP_TABLE SELECT @Rctid,@CODE
END
ELSE
BEGIN
SELECT @CODE=''
SELECT @DESC=rctDescription from RiskCategory where rctid=@PARENTID
WHILE(@PARENTID IS NOT NULL)
BEGIN
SELECT @PARENTCODE=rctCode from RiskCategory WHERE rctid=@PARENTID
IF @PARENTCODE='All'
SET @PARENTCODE=''
SELECT @CODE=@PARENTCODE +'.'+ @CODE
SELECT @PARENTID =rctParentID from Riskcategory where rctid= @PARENTID
END
SELECT @CODE=Substring(@CODE+@DESC,2,len(@CODE+@DESC))
INSERT INTO @TEMP_TABLE SELECT @RctID,@CODE
END
RETURN
END
在查询中使用如下
INSERT INTO @TopRiskCat
SELECT R.rskid
,a.topParentRiskCat AS TopLevelRiskCat
FROM RISKS R
INNER JOIN RiskAnalysis RA
ON R.rskId = RA.ranRiskId
INNER JOIN RiskCategory RC
ON RA.ranRiskAnalId = RC.rctId
CROSS APPLY fn_GetTopParentRiskCategory(RC.rctid) as a
它在2000年不起作用。我明天发布。请帮忙!!
我将不胜感激
由于
答案 0 :(得分:0)
由于您使用的功能始终只返回一个结果,因此您不需要交叉申请。应该可以将表值函数更改为标量值函数。
SQL声明
INSERT INTO @TopRiskCat
SELECT R.rskid
, a.topParentRiskCat AS TopLevelRiskCat
, fn_GetTopParentRiskCategory(RC.rctID)
FROM RISKS R
INNER JOIN RiskAnalysis RA ON R.rskId = RA.ranRiskId
INNER JOIN RiskCategory RC ON RA.ranRiskAnalId = RC.rctId
标量值函数
ALTER Function [dbo].[fn_GetTopParentRiskCategory] (@RctId int)
RETURNS Varchar(100) AS
BEGIN
DECLARE @topParentRiskCat Varchar(100)
DECLARE @PARENTID INT
DECLARE @GRANDPARENTID INT
DECLARE @CODE VARCHAR(100)
DECLARE @DESC VARCHAR(100)
DECLARE @PARENTCODE VARCHAR(100)
SELECT @PARENTID= rctParentID from RiskCategory where rctid=@RctId
SELECT @GRANDPARENTID= rctParentId from RiskCategory where rctid= @PARENTID
IF @GRANDPARENTID IS NULL
BEGIN
SELECT @topParentRiskCat = 'ALL'
END
ELSE
BEGIN
SELECT @CODE=''
SELECT @DESC=rctDescription from RiskCategory where rctid=@PARENTID
WHILE(@PARENTID IS NOT NULL)
BEGIN
SELECT @PARENTCODE=rctCode from RiskCategory WHERE rctid=@PARENTID
IF @PARENTCODE='All'
SET @PARENTCODE=''
SELECT @CODE=@PARENTCODE +'.'+ @CODE
SELECT @PARENTID = rctParentID from Riskcategory where rctid= @PARENTID
END
SELECT @CODE=Substring(@CODE+@DESC,2,len(@CODE+@DESC))
SELECT @topParentRiskCat = @CODE
END
RETURN @topParentRiskCat
END