2017-08-01 246 views
-2

在SQL Server 2012中,我想創建一個輸入參數爲 num1,num2,operation,out參數的存儲過程作爲結果。MS SQL Server 2012

如果你傳遞num1 = 1; num2 = 2;操作=添加,那麼我只需要通過輸出參數獲得結果3。

使用過程中的函數進行計算。

CREATE PROCEDURE taskname(@num1 int, @num2 int) 
AS 
BEGIN 
    DECLARE @result VARCHAR 

    SET @result = CAST ((num1 + @num2) AS INT) 

    PRINT 'The sum of ' + CAST(@num1 AS INT) + ' and ' + CAST(@num2 AS INT) + ' is ' + CAST((@num1 + @num2) AS INT) 

    PRINT @result 
END 

我試圖用這種方式。

+0

怎麼做,如果'操作= subtract'? – Arulkumar

+0

你甚至沒有跟着作業的第一行:'創建一個存儲過程,輸入參數爲num1,num2,operation,out參數爲結果。「 – Jamiec

+1

如果我們爲你做作業,你會學到什麼? –

回答

0
Create proc taskname(@num1 int, @num2 int,@operation nvarchar(max) ,@result int out) 
    as 
    begin 
    if(operation = 'ADD') 
BEGIN 
    set @result = @num1 + @num2 
    print 'the sum of '+cast(@num1 as nvarchar(max)) + ' and ' + cast(@num2 as nvarchar(max)) + ' is ' + cast(@result as nvarchar(max)) 
    print @result 
END 

if(operation = 'SUB') 
BEGIN 
    set @result = @num1 - @num2 
    print 'the subtraction of '+cast(@num1 as nvarchar(max)) + ' and ' + cast(@num2 as nvarchar(max)) + ' is ' + cast(@result as nvarchar(max)) 
    print @result 
END 

if(operation = 'MUL') 
BEGIN 
    set @result = @num1 * @num2 
    print 'the multiplication of '+cast(@num1 as nvarchar(max)) + ' and ' + cast(@num2 as nvarchar(max)) + ' is ' + cast(@result as nvarchar(max)) 
    print @result 
END 
    end 

要EXCUTE程序

DECLARE @result int 
    EXEC taskname 2 ,2,ADD,@result 

OUTPUT: -

the sum of 2 and 2 is 4 
    4 
+0

如果用於減法和乘法的操作該怎麼辦? – Queries

+0

我已更新我的答案,這是你在找什麼 – Ashu

+0

謝謝你的迴應。 – Queries