来自Sql中多个select语句的存储过程

时间:2013-05-02 11:14:06

标签: sql-server tsql

- >我想编写一个存储过程,它输出2个选择语句中的列

- >一个select语句中的列将是第二个select语句的输入

create procedure sp_proc
@inputId int
As 
Begin 

Select t1.ticketId AS ticket, 
t2.name AS NAME,
t3.status AS STATUS, 
t2.id ID
from table1 t1
Inner JOIN table2 t2 ON  t1.ticketId= t2.ticketId
INNER JOIN table3 t3 on t3.name = t2.name
WHERE t1.ticketId IS NOT NULL
AND t2.id = @inputId 


Select t1.ticketId, t2.name , D.desc, t2.id
from table1 t1
Inner JOIN table2 t2 ON  t1.ticketId= t2.ticketId
INNER JOIN( SELECt TOP 1 from table4 t4 ORDER BY t4.date  where t4.ticketId = ticket)AS D
ON t4.ticketId = t2.ticketId
WHERE t4.ticketId =ticket

当用户提供ticket, NAME,STATUS, ID , desc到proc

时,我想要@inputId

3 个答案:

答案 0 :(得分:0)

我会尝试在一个查询中组合所有内容。这是我的猜测,因为你似乎错过了一些东西:

SELECT
  t1.ticketId AS ticket, 
  t2.name AS NAME,
  t3.status AS STATUS, 
  t2.id AS ID,
  (SELECT TOP 1 desc FROM table4 WHERE t1.ticketId=table4.ticketId ORDER BY DESC) AS DESC
FROM table1 t1
INNER JOIN table2 t2 ON  t1.ticketId= t2.ticketId
INNER JOIN table2 t4 ON  t1.ticketId= t4.ticketId
INNER JOIN table3 t3 ON t3.name = t2.name

WHERE t1.ticketId IS NOT NULL AND t2.id = @inputId

但我不确定你想到哪儿来这里:

INNER JOIN( SELECt TOP 1 from table4 t4 ORDER BY t4.date  where t4.ticketId = ticket)AS desc
ON t4.ticketId = t2.ticketId

我猜你正在使用table4中的最新内容获取给定的ticketId ...所以我根据这个假设进行了查询。

答案 1 :(得分:0)

内联标量查询将起作用

create procedure sp_proc
@inputId int
As 

Select t1.ticketId AS ticket, 
t2.name AS NAME,
t3.status AS STATUS, 
t2.id ID,
[DESC] = (SELECT TOP(1) [DESC]
          from table4 t4
          where t4.ticketId = t1.ticketId
          ORDER BY t4.date)
from table1 t1
Inner JOIN table2 t2 ON  t1.ticketId= t2.ticketId
INNER JOIN table3 t3 on t3.name = t2.name
WHERE t1.ticketId IS NOT NULL
AND t2.id = @inputId;
GO

答案 2 :(得分:0)

我可以通过单一查询实现它。

创建过程sp_proc @inputId int 正如

选择t1.ticketId AS票, t2.name AS NAME, t3.status作为状态, t2.id ID, t4Description。[DESC] 来自table1 t1

内部联接表2 t2 ON t1.ticketId = t2.ticketId

关于t3.name = t2.name

的INNER JOIN table3 t3

外部申请(

              SELECT TOP 1 [desc]
              FROM table4 t4
              WHERE t4.ticketId = t1.ticketId
              ORDER BY t4.[date] DESC

        ) t4Description

WHERE      t1.ticketId不是NULL      AND t2.id = @inputId