否则如果在存储过程中避免

时间:2016-06-28 21:55:03

标签: sql-server stored-procedures

我编写了以下sproc以搜索记录并终止于它无法使用硬编码错误消息找到它的表。

它有效,但我希望它更聪明。有任何建议请。

Create PROCEDURE [dbo].[dummy_test]

@ID NVARCHAR(50)

AS
BEGIN


Declare @TID Table (TID bigint not null)    
declare @TransId bigint     

-- Search for @TID
insert into @TID
Select TID from x..tables  where   EID = @ID 

Select @TransId = (select TID from @TID)

If not exists 
(select top 1 1  from x..table7  where TID = @TransId)
print 'B'
else
If not exists
(select top 1 1  from x..table6  where TID=  @TransId)
print 'C'
else

If not exists
(select top 1 1  from x..table0  where TID=  @TransId)
print 'D'
else

If not exists
(select top 1 1  from x..table1  where TID =  @TransId)
print 'E'
else

If not exists
(select top 1 1  from x..table2  where TID =  @TransId)
print 'F'
else

If not exists
(select top 1 1  from x..table3  where TID =  @TransId)
print 'G'

delete @TID


END

1 个答案:

答案 0 :(得分:0)

我可以建议的唯一改进就是在你的代码中删除Table变量,这完全没必要,并做了类似......

declare @TransId bigint     

Select @TransId = TID from x..tables  where   EID = @ID  

除了上面的代码之外,我认为你不能简化剩余的代码,因为它正在检查不同表中是否存在@TransId