从存储过程中检索两个值

时间:2009-09-22 12:16:36

标签: sql stored-procedures

有人可以告诉我如何组合计算邮件数量和未读邮件数量的两个SQL语句吗?它无效的两个有两个陈述但我不知道要搜索什么来得到我正在寻找的答案。提前谢谢。

CREATE PROCEDURE dbo.GetMessages (
  @username nchar(12),
  @isCount bit,
  @message_count int OUTPUT,
  @unread_message_count int OUTPUT
) AS

IF @isCount = 1
BEGIN
  SET @message_count = 
  (
    SELECT        COUNT(*)
    FROM          messages
    WHERE         usernameTo = @username
  )

  SET @unread_message_count =
  (
    SELECT        COUNT(*)
    FROM          messages
    WHERE         usernameTo = @username AND message_read = 1
  )
END
ELSE
BEGIN
  SELECT        *
  FROM          messages
  WHERE         usernameTo = @username
END

4 个答案:

答案 0 :(得分:2)

select count(*) as TotalCount, 
    count(case when message_read = 1 then 1 else null end) as ReadMessageCount, 
    count(case when message_read <> 1 then 1 else null end) as UnreadMessageCount
from messages
where usernameTo = 'jsmith'

答案 1 :(得分:2)

首先,您希望将其拆分为两个存储过程。如果您曾经使用一点来确定要执行哪个代码块,那么您可能会尝试将过多的代码放入一个存储过程中。

CREATE PROCEDURE dbo.GetMessageCount (
  @username nchar(12),
  @message_count int OUTPUT,
  @unread_message_count int OUTPUT
) AS

SELECT
    @message_count = SUM(CASE WHEN message_read = 1 THEN 1 ELSE 0 END),
    @unread_message_count = SUM(CASE WHEN message_read <> 1 THEN 1 ELSE 0 END)
FROM messages
WHERE usernameTo = @username

GO

您可以为存储的procdure执行类似的操作,以获取特定用户的所有消息。您不想在此处使用“选择*”。您应该始终列出所需的特定列。我列出了一些示例列。

CREATE PROCEDURE dbo.GetMessagesByUser (
    @username nchar(12)
) AS

  SELECT
      MessageID,
      MessageSubject,
      MessageContent,
      MessageFromUser,
      MessageCreatedDate
  FROM          messages
  WHERE         usernameTo = @username

GO

答案 2 :(得分:1)

这取决于你正在使用的SQL,但是,例如,在PostgreSQL中它会是这样的:

SELECT
    COUNT(*) AS messages,
    COUNT( CASE WHEN message_read=1 THEN 1 ELSE NULL END ) AS unreads,
    COUNT( CASE WHEN message_read=1 THEN NULL ELSE 1 END ) AS reads
FROM messages WHERE usernameTo='someone';

这应该有所帮助。

答案 3 :(得分:0)

SELECT COUNT(*) AS total_messages,      
       SUM(CASE WHEN message_read=1 THEN 1 END) as read, 
       SUM(CASE WHEN message_read=0 THEN 1 END) as unread
FROM mesages WHERE usernameTo='username';