创建一个将两个表结果合并为一个的存储过程?

时间:2019-10-03 04:14:33

标签: sql sql-server tsql

下面的代码运行良好,但是在两个不同的表中显示结果。我想在一张表中显示存储过程的结果。

USE [LSM2]
GO

-- StoredProcedure [dbo].[Proc_TotalBooks]

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Proc_TotalBooks]
AS
BEGIN
    SELECT COUNT([Book ID]) AS TotalBooks FROM BookRegistration;
    SELECT COUNT([Book ID]) AS BorrowedBooks FROM Borrowing;    
END

enter image description here

4 个答案:

答案 0 :(得分:1)

您可以通过使用变量来实现

您的查询看起来像这样

ng add @angular/material

或者您可以使用完全加入

declare @A int
declare @B int

SELECT @A = COUNT([Book ID])  FROM BookRegistration; 
SELECT @B =COUNT([Book ID]) FROM Borrowing; 

SELECT @A AS TotalBooks, @B   AS BorrowedBooks

答案 1 :(得分:0)

我认为这可能对您有所帮助:两个带有Description的值显示。如果您愿意,也可以使用Clause来创建新表

 ALTER PROCEDURE [dbo].[Proc_TotalBooks]
            AS
            BEGIN
                SELECT 'Total Books' as Description,COUNT([Book ID]) AS TotalBooks  FROM BookRegistration;
            union all
                SELECT 'BorrowedBooks' as Description,COUNT([Book ID]) AS BorrowedBooks FROM Borrowing;    
            END

答案 2 :(得分:0)

您可以使用union all

SELECT 'TotalBooks', COUNT([Book ID]) AS total
FROM BookRegistration
UNION ALL
SELECT 'Borrowed', COUNT([Book ID])
FROM Borrowing;

这将产生两行。

或两列的嵌套子查询:

SELECT (SELECT COUNT([Book ID]) FROM BookRegistration) as TotalBooks,
       (SELECT COUNT([Book ID]) FROM Borrowing) as BorrowedBooks;  

或将条件移至FROM子句:

SELECT t.TotalBooks, b.BorrowedBooks
FROM (SELECT COUNT([Book ID]) AS TotalBooks FROM BookRegistration
     ) t CROSS JOIN
     (SELECT COUNT([Book ID]) AS BorrowedBooks FROM Borrowing
     ) b  ;

答案 3 :(得分:0)

选择(从BookRegistration的SELECT COUNT([[图书ID])从AS TotalBooks,选择(从借的的SELECT COUNT([Book ID])从AS借阅的图书)