SQL Query多个if else条件块

时间:2014-02-04 10:02:05

标签: sql-server database tsql

我已经创建了sql proc来从数据库中选择记录 它成功执行但没有返回任何内容

谁能告诉我哪里出错了?

CREATE PROC [dbo].[bb_EmailSentStatus] 
 @type varchar
AS 
 SET NOCOUNT ON 
 SET XACT_ABORT ON  

 BEGIN TRAN


 IF (@type='pending')
 BEGIN
  SELECT [Mail_Track_Id], [FromName],[FromEmail],[ToName],[ToEmail],[ReplyTo],
         [Subject],[CreatedDate],[ModifiedDate],[Server_Msg],[FromSource] 
  FROM [dbo].[Mail_Track] 
  WHERE Active_Status=1 AND Sent_Status IS NULL
 END
 ELSE IF(@type='failed')
 BEGIN
  SELECT [Mail_Track_Id], [FromName],[FromEmail],[ToName],[ToEmail],[ReplyTo],
         [Subject],[CreatedDate],[ModifiedDate],[Server_Msg],[FromSource] 
  FROM [dbo].[Mail_Track] 
  WHERE Active_Status=1 AND Sent_Status = 0
 END
 ELSE IF(@type='success')
 BEGIN
  SELECT [Mail_Track_Id], [FromName],[FromEmail],[ToName],[ToEmail],[ReplyTo],
         [Subject],[CreatedDate],[ModifiedDate],[Server_Msg],[FromSource] 
  FROM [dbo].[Mail_Track] 
  WHERE Active_Status=1 AND Sent_Status = 1
 END
COMMIT

2 个答案:

答案 0 :(得分:8)

您尚未声明varchar参数的长度。将其更改为:

@type varchar(50) 

如果您没有指定长度,varchar只需要1个字符的defalt。作为一个好习惯,请记住明确定义变量类型的长度,例如varchar,nvarchar等。

如果使用convert function将值转换为varchar,nvarchar字段,则需要30个字符进行defult,但即使这样,作为一个好习惯,您应该始终声明一个特定的长度。

答案 1 :(得分:3)

您还可以通过在参数

的基础上更改where子句来消除多个if else
CREATE PROC [dbo].[Bb_emailsentstatus] @type VARCHAR(10) 
AS 
SET nocount ON 
SET xact_abort ON 


SELECT [mail_track_id], 
             [fromname], 
             [fromemail], 
             [toname], 
             [toemail], 
             [replyto], 
             [subject], 
             [createddate], 
             [modifieddate], 
             [server_msg], 
             [fromsource] 
      FROM   [dbo].[mail_track] 
      WHERE  (@type = 'pending'  AND
                active_status = 1 
                AND sent_status IS NULL )
             OR 
             (@type = 'failed'  AND 
                active_status = 1 
                AND sent_status = 0 )
             OR 
             (@type = 'success'  AND    
                active_status = 1 
             AND sent_status = 1  )