简体   繁体   English

如何定义返回表的存储过程?

[英]How do I define a stored procedure that returns table?

For example I have this stored procedure: 例如,我有这个存储过程:

create procedure MyStoredProcedure
as
begin
    select  *
    from X,Y
    where x.Id = Y.ID
end
return @table table(X.tTitle, Y.Description)

I want return table and when use table in another query 我想要返回表以及在其他查询中使用表时

Stored procedures cannot 1 be composed into other queries as a source of rows - is there a reason why it has to be a stored procedure? 存储过程不能1组成到其他查询作为行的来源-是有一个原因是一个存储过程? A user defined function has almost the same amount of expressability as a stored procedure and can easily be a source of rows in the FROM clause of another query. 用户定义的函数具有与存储过程几乎相同的可表达性,并且可以轻松地成为另一个查询的FROM子句中的行源。

Something like: 就像是:

create function MyFunction()
returns table
as
return (select  X.tTitle,Y.Description
    from X
    inner join Y
        on x.Id = Y.ID)

1 Ignoring INSERT ... EXEC since it does nothing for composition, and OPENROWSET isn't always a viable approach. 1忽略INSERT ... EXEC因为它对合成没有任何作用,并且OPENROWSET并不总是可行的方法。

Try this: 尝试这个:

create procedure MyStoredProcedure
as
begin

select  X.*,Y.*
    From X INNER JOIN Y ON X.Id=Y.ID

end

This will select all data from tables X and Y. 这将从表X和Y中选择所有数据。

Try This Way: 尝试这种方式:

CREATE PROCEDURE [dbo].[MyStoredProcedure]

    AS
    BEGIN
        -- SET NOCOUNT ON added to prevent extra result sets from
        -- interfering with SELECT statements.
        SET NOCOUNT ON;
        Declare @ID int
         set @ID =(select ID From X INNER JOIN Y ON X.Id=Y.ID)
         IF @ID > 0
         BEGIN
               return @table table(X.tTitle,Y.Description)
         END
    END

you can simply Create a Procedure and then, Try this: 您可以简单地创建一个Procedure ,然后尝试以下操作:

CREATE PROCEDURE MyStoredProcedure
AS
    BEGIN
        SELECT  tTitle ,
                Description
        FROM    X
                JOIN Y ON Y.ID = X.ID
    END

You can use temp tables or table variables. 您可以使用临时表或表变量。 Like this: 像这样:

CREATE TABLE #TABLE
(
COLUMN DEFINITION
)

INSERT INTO #TABLE
EXEC <YOUR STORED PROCEDURE>
SELECT *
FROM #TABLE

DROP TABLE #TABLE

You can insert your stored procedure inside the temp table so you can use it as well as a table. 您可以将存储过程插入temp表中,以便可以将其与表一起使用。 Note that temp table names should start with #. 请注意,临时表名称应以#开头。

Somethings like this you most write 你最喜欢写的东西

CREATE PROCEDURE <SP_Name>
AS
BEGIN
    Select ......
End

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM