2011-01-10 23 views
34

我在SQL Server 2005中有多個變量的存儲過程,我想使用select語句設置這些變量的值。所有這三個變量都來自同一個表,並且應該有一種方法來使用一個select語句來設置它們,而不是我現在具有的方式,如下所示。請幫我弄明白。SQL存儲過程使用SELECT設置變量

DECLARE @currentTerm nvarchar(max) 

DECLARE @termID int 

DECLARE @endDate datetime 

SET @currentTerm = 
(
    Select CurrentTerm from table1 where IsCurrent = 1 
) 

SET @termID = 
(
    Select TermID from table1 where IsCurrent = 1 
) 

SET @endDate = 
(
    Select EndDate from table1 where IsCurrent = 1 
) 

回答

66
select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate 
    from table1 
    where IsCurrent = 1 
+0

我一直在寫了類似的聲明。比較我的語句和這個語句,我一直接受@currentTerm = CurrentTerm作爲變量,返回值爲NULL。有什麼建議麼? – srbhattarai 2015-09-04 07:11:15

12

您目前的方法所具有的一個優點是,如果謂詞返回多行,則會引發錯誤。重現您可以使用的內容。

SELECT @currentTerm = currentterm, 
     @termID = termid, 
     @endDate = enddate 
FROM table1 
WHERE iscurrent = 1 

IF(@@ROWCOUNT <> 1) 
    BEGIN 
     RAISERROR ('Unexpected number of matching rows', 
       16, 
       1) 

     RETURN 
    END