简体   繁体   中英

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? 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.

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.

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.

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:

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. Note that temp table names should start with #.

Somethings like this you most write

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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