使用SQL中的联合选择创建视图或函数

时间:2018-08-03 08:27:12

标签: sql sql-server

我在SQL Server 2012数据库中有一个具有以下布局的表:

motherID引用的是同一表中的ID

我们100%认为表格中没有死锁。

我创建了一个存储过程,该过程输出从通用ID凝视的所有ID

即:

ID    MotherID
1     1
2     1
3     1
4     2
5     2
6     4

当我选择1时,它会返回

1,2,3,4,5,6

凝视4时

4, 6

从2开始

2,4,5,6

但是我想在另一个选择的内部联接中使用结果。

据我所知,必须将存储过程重写为视图或函数。

有人可以帮助我吗?

下面是存储过程

ALTER PROCEDURE GetAll( @parent int)
AS
BEGIN
     SET NOCOUNT ON; 

WITH Children AS        
(

SELECT ID, MotherID FROM Test WHERE MotherID = @Parent  and ID!=@Parent
UNION ALL 

    SELECT e.ID, e.MotherID FROM Test e            
    INNER JOIN Children e2 on e.MotherID = e2.ID)              
    SELECT ID into #temp from Children  
    -- there is more here, thats why i use #temp    

    insert into #temp values (@parent )            
    select * from #temp order by id
    drop table #temp

END
GO

和表格:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Test](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [MotherID] [int] NOT NULL,
 CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

ALTER TABLE [dbo].[Test]  WITH CHECK ADD  CONSTRAINT [FK_Test_Test] FOREIGN KEY([ID])
REFERENCES [dbo].[Test] ([ID])
GO

ALTER TABLE [dbo].[Test] CHECK CONSTRAINT [FK_Test_Test]
GO

ALTER TABLE [dbo].[Test]  WITH CHECK ADD  CONSTRAINT [FK_Test_Test1] FOREIGN KEY([MotherID])
REFERENCES [dbo].[Test] ([ID])
GO

ALTER TABLE [dbo].[Test] CHECK CONSTRAINT [FK_Test_Test1]
GO

ID  MotherID
1   1
2   1
3   1
4   2
5   2
6   4

1 个答案:

答案 0 :(得分:0)

CREATE FUNCTION GetAll
(
    @parent INT
)
RETURNS TABLE
AS
RETURN WITH Children
       AS (SELECT ID,
                  MotherID
           FROM test
           WHERE MotherID = @parent
                 AND ID != @parent
           UNION ALL
           SELECT e.ID,
                  e.MotherID
           FROM test e
               INNER JOIN Children e2
                   ON e.MotherID = e2.ID)
SELECT @parent AS Id
UNION all
SELECT ID
FROM Children;

然后您可以像使用它一样

Select * from GetAll(1);