首先,我必须承认我对sql server的
recursive CTE’s不是很熟悉,但我认为这是最好的方法.
我有一个表tabData.它的PK名为idData,并且有一个自引用FK fiData.
所以fiData引用父记录和SELECT * FROM tabData WHERE idData = fiData返回父记录的所有数据.这很简单快捷.但是如何让自然顺序中的所有父母从特定记录中获取?
假设有一个子节点(idData = 4)有3个父节点(第一个父节点是idData = 3的记录):
idData fiData 4 3 3 2 2 1 1 NULL
我认为递归CTE是要走的路,但我的语法并不好.
那么实现返回所有父母的CTE的正确方法是什么?
我试过跟随,但它给了我错误的结果(3,4而不是3,2,1):
(为了测试它,我为你和你创建了一个临时表)
IF (NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'tabData_Temp')) BEGIN CREATE TABLE [dbo].[tabData_Temp]( [idData] [int] NOT NULL,[fiData] [int] NULL,CONSTRAINT [PK_tabData_Temp] PRIMARY KEY CLUSTERED ( [idData] ASC )WITH (PAD_INDEX = OFF,STATISTICS_NORECOMPUTE = OFF,IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON,ALLOW_PAGE_LOCKS = ON) ); ALTER TABLE [dbo].[tabData_Temp] WITH CHECK ADD CONSTRAINT [FK_tabData_Temp] FOREIGN KEY([fiData]) REFERENCES [dbo].[tabData_Temp] ([idData]); ALTER TABLE [dbo].[tabData_Temp] CHECK CONSTRAINT [FK_tabData_Temp]; INSERT INTO [dbo].[tabData_Temp](idData,fiData)VALUES(1,NULL); INSERT INTO [dbo].[tabData_Temp](idData,fiData)VALUES(2,1); INSERT INTO [dbo].[tabData_Temp](idData,fiData)VALUES(3,2); INSERT INTO [dbo].[tabData_Temp](idData,fiData)VALUES(4,3); END /* here comes the (not working) recursive CTE */ Declare @fiData int; SET @fiData = 3; WITH PrevIoUsClaims(idData,fiData) AS( SELECT parent.idData,parent.fiData FROM tabData_temp parent WHERE parent.idData = @fiData UNION ALL SELECT child.idData,child.fiData FROM tabData_temp child INNER JOIN PrevIoUsClaims parent ON parent.idData = child.fiData ) SELECT idData FROM PrevIoUsClaims; /* end of recursive CTE */ DROP TABLE [dbo].[tabData_Temp];
先谢谢你.
解决方法
改为:
INNER JOIN PrevIoUsClaims parent ON parent.fiData = child.idData
给我你想要的结果.