变量声明

时间:2013-06-18 02:56:39

标签: sql sql-server sql-server-2008 tsql

         `DECLARE @MYACCOUNT CHAR(2),
         @REPORTTYPE CHAR(1),
         @BRANCHCODE CHAR(3)


         SELECT @MYACCOUNT='SV',
         @REPORTTYPE='D',
         @BRANCHCODE='001'

         IF NOT EXISTS(SELECT 1 FROM TBL_Category WHERE CategoryType=@MYACCOUNT)
         SELECT 'INVALID ACCOUNT NAME IS : '+@MYACCOUNT

         ELSE IF NOT EXISTS(SELECT 1 FROM TBL_Category WHERE CatGroup=@REPORTTYPE)
         SELECT 'INVALID REPORT NAME IS : '+@REPORTTYPE

         ELSE IF NOT EXISTS(SELECT 1 FROM BranchMaster WHERE MBranchCode=@BRANCHCODE)
         SELECT 'INVALID BRANCH CODE IS : '+@BRANCHCODE

         ELSE
           SELECT M.MBranchCode, SUM(M.MMiscBaln) FROM MasterTable M, TBL_Category T
           WHERE T.CategoryCode=M.MAcType
           AND T.CategoryType=@MYACCOUNT
           AND T.CatGroup=@REPORTTYPE
           AND M.MBranchCode=@BRANCHCODE
           GROUP BY M.MBranchCode`

我想要一个解决方案,当我在变量中输入错误的数据时,它应该抛出错误信息。可能存在多个错误,但应显示这些变量的错误。 例如:

如果我输入了值:

                `@BRANCHCODE='002'
               @REPORTTYPE='A'
               @MYACCOUNT='SQ'`

@BRANCHCODE是正确的。然后它应该抛出@REPORTTYPE和@MYACCOUNT错误的消息。

1 个答案:

答案 0 :(得分:2)

收集错误消息,如果没有返回查询结果,则返回或提高收集的错误消息。

Declare @a Table (a int,b int,c int)

insert into @a Values(1,2,3),(4,4,4)

Declare @va int=2
Declare @vb int=2
Declare @vc int=2

Declare @error Varchar(100)=''
if not exists(select * from @a where a=@va)
   Select @Error=@Error + 'Invalid va ' + Cast(@va as Varchar(10)) + Char(13)+Char(10)
if not exists(select * from @a where b=@vb)
   Select @Error=@Error + 'Invalid vb ' + Cast(@vb as Varchar(10)) + Char(13)+Char(10)
if not exists(select * from @a where c=@vc)
   Select @Error=@Error + 'Invalid vc ' + Cast(@vc as Varchar(10)) + Char(13)+Char(10)
if len(@Error)>0 select @Error
else
  Select * from @a where a=@va and b=@vb and c=@vc