2012-05-03 33 views
-1

我正在使用Sql Server 2008.在我的sql文件中,我定義了5個局部變量(它們都是int),並將它們全部設置爲0。 (不在循環中)。每次操作之後,我需要將局部變量的值重置爲0.現在,我在每次操作後手動將所有變量設置爲0。是否有更好的方法可以將它們全部重置爲0,也許可以通過調用某個函數而不是以maunally的方式執行它?要調用一些sql代碼來重置本地變量的值

DECLARE @int1 int 
DECLARE @int2 int 
DECLARE @int3 int 
DECLARE @int4 int 
DECLARE @int5 int 

SET @int1 = 0 
SET @int2 = 0 
SET @int3 = 0 
SET @int4 = 0 
SET @int4 = 0 

-- Operation 1 
SELECT * FROM Orders 

-- Reset values (Number of times the reset code written: 1) 

SET @int1 = 0 
SET @int2 = 0 
SET @int3 = 0 
SET @int4 = 0 
SET @int4 = 0 
-------------------- END OF OPERATION 1 and RESETTING VARIABLES --------------- 

-- Operation 2 

SELECT * FROM Lines 

-- Reset values (Number of times the reset code written: 2) 

SET @int1 = 0 
SET @int2 = 0 
SET @int3 = 0 
SET @int4 = 0 
SET @int4 = 0 
-------------------- END OF OPERATION 2 and RESETTING VARIABLES --------------- 

-- Operation 3 

SELECT * FROM Customers 

-- Reset values (Number of times the reset code written: 3) 

SET @int1 = 0 
SET @int2 = 0 
SET @int3 = 0 
SET @int4 = 0 
SET @int4 = 0 
-------------------- END OF OPERATION 3 and RESETTING VARIABLES --------------- 

-- Operation 4 

SELECT * FROM Address 

-- Reset values (Number of times the reset code written: 4) 

SET @int1 = 0 
SET @int2 = 0 
SET @int3 = 0 
SET @int4 = 0 
SET @int4 = 0 
-------------------- END OF OPERATION 4 and RESETTING VARIABLES --------------- 

-- Operation 5 

SELECT * FROM Accounts 

-- Reset values (Number of times the reset code written: 5) 

SET @int1 = 0 
SET @int2 = 0 
SET @int3 = 0 
SET @int4 = 0 
SET @int4 = 0 
-------------------- END OF OPERATION 5 and RESETTING VARIABLES --------------- 

由於這是顯而易見的,重置局部變量已經被寫入5倍(按確定「的次數重置編寫的代碼:#」)。有沒有更好的方法來調用一個執行重置的函數,以便我只需要調用一個函數,例如ResetVaraibles(),該函數將具有重置局部變量的代碼。現在更清楚了嗎?

+2

你有沒有考慮過發佈實際的代碼而不是窮人的描述? –

+0

你想這樣做的事實表明你可能會錯誤地接近真正的問題 –

+0

真正的問題是我不想寫重置代碼N次。我在尋找可重複使用的代碼,可以通過簡單地調用該可重用代碼N次來幫助我做到這一點。通常,這可以通過以任何測試語言調用函數來輕鬆實現。 – user1274655

回答

0

你可以有5個輸出參數的存儲過程。

create procedure ResetTo0 
    @int1 int out, 
    @int2 int out, 
    @int3 int out, 
    @int4 int out, 
    @int5 int out 
as 

set @int1 = 0 
set @int2 = 0 
set @int3 = 0 
set @int4 = 0 
set @int5 = 0 

它會這樣調用。

exec ResetTo0 @int1 out, @int2 out, @int3 out, @int4 out, @int5 out 

但我不認爲你獲得多少(如果有的話)相比,使用選擇重置值。

select @int1 = 0, @int2 = 0, @int3 = 0, @int4 = 0, @int5 = 0 
0

方式1:斷開並連接到SQL Server。

方式2:Ctrl-A Ctrl-C Ctrl-N Ctrl-V將代碼複製到新窗口。