[英]How can I join different result of a query from a table to another table in a stored procedure
I have tree tables:我有树表:
I want to write a stored procedure which return all the references with the Stock of them.我想编写一个存储过程,它返回所有带有 Stock 的引用。
Invoices are two types: input (which add to stock) and output (which subtract from stock).发票有两种类型:输入(添加到库存)和 output(从库存中减去)。
It means I have to run a query for two times on InvoiceHeader joining InvoiceDetails on for having inputs of all the references and one for having outputs of the references.这意味着我必须在 InvoiceHeader 上运行两次查询,加入 InvoiceDetails 以获取所有引用的输入和一次以获取引用的输出。
Then I have to join these two queries to the products and make a new field (remain) which minus output from input for each reference.然后我必须将这两个查询加入产品并创建一个新字段(剩余),从每个参考的输入中减去 output。
The results should be like this:结果应该是这样的:
Reference Input Output Remain
X 5 2 3
Y 10 3 7
Z 1 1 0
How can I write the procedure?怎么写程序?
Could you please precise what do you would like to know?你能准确地说你想知道什么吗? How to pass 3 values to output, select 3 values, or 'do the job' inside the procedure?
如何将 3 个值传递给 output、select 3 个值,或在过程中“完成工作”?
SQL server supports having more than one output value. SQL 服务器支持具有多个 output 值。 So If that is your issue you can use for example that blog post which describes how to do that.
因此,如果这是您的问题,您可以使用例如描述如何做到这一点的博客文章。 If your goal is to have procedure which selects these values, but they will not be used in the future you can just... select them in the procedure body... as per below
如果您的目标是拥有选择这些值的程序,但将来不会使用它们,您可以... select 它们在程序主体中...如下所示
create procedure as X
begin
select ...
select ...
select ...
end
You can write a procedure with table result set output, like this:您可以使用表结果集 output 编写一个过程,如下所示:
CREATE PROCEDURE my_stored_proc
@param1 INT,
@param2 INT
AS
BEGIN
SELECT T.field1,
T.field2
FROM my_table AS T
WHERE T.field3 = @param1
AND T.field4 = @param2
END
so when executing the procedure, you'd get the result same as executing SELECT statement.因此在执行该过程时,您会得到与执行 SELECT 语句相同的结果。
In sql-server (mssql) you can "collect" the output result-set like this:在 sql-server (mssql) 中,您可以像这样“收集” output 结果集:
DECLARE @output1 AS TABLE (field1 INT, field2 INT)
INSERT INTO @output1
EXEC my_stored_proc @param1 = 1, @param2 = 2
you can then use the collected output with any other query, like this:然后,您可以将收集到的 output 与任何其他查询一起使用,如下所示:
SELECT T.field2 * 2 + T.field1
FROM @output1 AS T
JOIN some_table6 AS T6 ON T6.id = T.field1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.