2015-02-08 95 views
0

我有一個執行另一個過程的過程,我需要將結果保存到一個變量中。將執行過程結果保存到SQL Server 2008中的var

我該怎麼做?

ALTER PROCEDURE sp_GetDetailsByUserId 
    @userId int 
AS 
BEGIN 
    SELECT 
     usr.FirstName, usr.LastName, usr.UserName, usr.Email 
    FROM 
     [User] usr 
    WHERE 
     usr.UserID = @userId 

    EXEC sp_GenerateRandomPass @userId // this result need to be inside a var 
END 

我是初學者,需要幫助。

謝謝。

+0

你的意思是'var'。 'sp_GenerateRandomPass'過程是否返回表或什麼? – 2015-02-08 07:49:36

+0

備註:您應該**不要**爲存儲過程使用'sp_'前綴。微軟已經保留了這個前綴以供自己使用(參見*命名存儲過程*)](http://msdn.microsoft.com/en-us/library/ms190669%28v=sql.105%29.aspx),以及你將來有可能冒着名字衝突的風險。 [這對你的存儲過程性能也是不利的](http://www.sqlperformance.com/2012/10/t-sql-queries/sp_prefix)。最好只是簡單地避免使用'sp_'並將其他內容用作前綴 - 或者根本沒有前綴! – 2015-02-08 09:07:59

回答

0

可以聲明或者你可以使用一個臨時表

ALTER PROCEDURE sp_GetDetailsByUserId 
    @userId int 
    AS 
    BEGIN 
    SELECT usr.FirstName, usr.LastName, usr.UserName, usr.Email 
    FROM [User] usr 
    WHERE usr.UserID = @userId 

    declare @tbl table (the columns should be compatible with the result columns) 

    insert into @tbl 
    exec sp_GenerateRandomPass @userId // this result need to be inside a var 

END 

不是Temptable你可以這樣做:

ALTER PROCEDURE sp_GetDetailsByUserId 
    @userId int 
    AS 
    BEGIN 
    SELECT usr.FirstName, usr.LastName, usr.UserName, usr.Email 
    FROM [User] usr 
    WHERE usr.UserID = @userId 

    create table #tempTable(the columns should be compatible with the result columns) 

    insert into #tempTable 
    exec sp_GenerateRandomPass @userId // this result need to be inside a var 

END 
0

你可以改變程序?具有輸出參數可能是最好的,假設select始終只返回一行。

exec sp_GenerateRandomPass @userId, @password output 

輸出參數的工作原理是這樣的:

ALTER PROCEDURE sp_GenerateRandomPass 
@userId int, 
@password varchar (100) output 
AS 
BEGIN 
    -- Magic happens 
    set @password = 'xxxx' 
END 

其他選項是改變GenerateRandomPass是一個標量函數,你可以直接在你的程序將值分配給一個變量

而且,請不要在「sp_」前面加上你的過程前綴,它只適用於內置程序。

0

您需要修改sp_GenerateRandomPass,將此存儲過程中的查詢結果存儲到temptable。查找更多關於temptable

臨時表將在存儲過程中訪問。所以你可以使用它在sp_GetDetailsByUserId